<?php
include_once('../libs/main.php');
include_once('checkLogin.php');

$newAcqObj    = new newlead();
$dependantObj = new dependant();
$clinicObj    = new clinic();

if (isset($_REQUEST['act']) && $_REQUEST['act']=='load') {

    $records = $_REQUEST['length'];
    $start   = ($_GET['start'] ?? 0);
    $limit   = array('start'=>$start,'record'=>$records);

    $where = " 1=1 ";

    if(!empty($_REQUEST['firstname'])){
        $where .= " AND d.dependant_fname LIKE '%".w::e($_REQUEST['firstname'])."%' ";
    }
    if(!empty($_REQUEST['lastname'])){
        $where .= " AND d.dependant_lname LIKE '%".w::e($_REQUEST['lastname'])."%' ";
    }
    if(!empty($_REQUEST['clinic_id'])){
        $where .= " AND n.newlead_clinic_id = '".($_REQUEST['clinic_id'])."' ";
    }
    if(!empty($_REQUEST['startdate']) && !empty($_REQUEST['enddate'])){
        $where .= " AND DATE(n.newlead_created_at) BETWEEN '".($_REQUEST['startdate'])."' AND '".($_REQUEST['enddate'])."' ";
    }

    $tables  = array('tbl_dependant d','tbl_clinic c');
    $jfields = array(
        'n.newlead_patient_id = d.dependant_id',
        'c.clinic_id = n.newlead_clinic_id'
    );
    $jtype   = array('LEFT','LEFT');

    $orderby = array(" n.newlead_created_at DESC ");

    $data = array(
        'where'=>$where,'joinTables'=>$tables,'joinFields'=>$jfields,'joinTypes'=>$jtype,
        'orderBy'=>$orderby,'limit'=>$limit
    );

    $acqDetails  = $newAcqObj->getAllRecords($data);
    $recordsTotal = $newAcqObj->getAllCount($data);

    if ($acqDetails && count($acqDetails)>0){
        foreach ($acqDetails as $lead){
            $patientInfo = "<b>ID:</b> ".$lead->dependant_id."<br/>
                            <b>Name:</b> ".w::d($lead->dependant_fname)." ".w::d($lead->dependant_lname)."<br/>
                            <b>Phone:</b> ".w::d($lead->dependant_phone)."<br/>
                            <b>Email:</b> ".w::d($lead->dependant_email_address);

            $clinicInfo = "<b>Clinic:</b> ".$lead->clinic_name."<br/>
                           <b>Email:</b> ".$lead->clinic_email."<br/>
                           <b>Phone:</b> ".$lead->clinic_phone."<br/>
                           <b>Website:</b> ".$lead->clinic_website;

            $newLead = "<b>Source:</b> ".$lead->newlead_source."<br/>
                           <b>Origin:</b> ".($lead->newlead_origin)."<br/>
                           <b>MatchBy:</b> ".$lead->match_by; 

            $acqCreated = "<b>Created At:</b> ".$lead->newlead_created_at;
                           

            $response[] = array($patientInfo,$clinicInfo,$newLead,$acqCreated);
        }
        $result = array('recordsFiltered'=>$recordsTotal,'recordsTotal'=>$recordsTotal,'data'=>$response);
    } else {
        $result = array('recordsFiltered'=>0,'recordsTotal'=>0,'data'=>array());
    }
    echo json_encode($result);
    exit;
}
include_once('../libs/routs.php');
?>
