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

$referObj    = new referredByClinic();
$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 r.clinic_id = '".($_REQUEST['clinic_id'])."' ";
    }

    $tables  = array('tbl_dependant d','tbl_clinic c');
    $jfields = array(
        'r.patient_id = d.dependant_id',
        'c.clinic_id = r.clinic_id'
    );
    $jtype   = array('LEFT','LEFT');

    $orderby = array(" r.id DESC ");

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

    $referDetails  = $referObj->getAllRecords($data);
    $recordsTotal  = $referObj->getAllCount($data);

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

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

            $refferalDetail = "<b>type:</b> ".$row->type."<br/>
                              <b>ReferVia:</b> ".$row->referVia."<br/>
                              <b>ReferOn:</b> ".$row->referOn."<br/>
                              <b>Reason:</b> ".$row->reason;

            $response[] = array($patientInfo,$clinicInfo,$refferalDetail);
        }
        $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');
?>
