<?php
// assignPointToClinicList.php

// Include main file
include_once('../libs/main.php');
include_once('checkLogin.php');

$agencyClinicPointObj = new agencyclinic_point(); 

if (isset($_REQUEST['act']) && $_REQUEST['act']=='load') {
    
    $records = $_REQUEST['length'];
    $start   = ($_GET['start'] ?? 0);
    $limit   = array('start'=>$start,'record'=>$records);

    $where = " 1=1 AND a.admin_id IS NOT NULL ";

    if(!empty($_REQUEST['clinic_id'])){
        $where .= " AND a.clinic_id = '".($_REQUEST['clinic_id'])."' ";
    }

    $tables  = array('tbl_clinic c','tbl_admin ad');
    $fields = array('a.*, c.clinic_name, ad.admin_fname, ad.admin_lname');
    $jfields = array(
        'c.clinic_id = a.clinic_id', 
        'ad.admin_id = a.admin_id'
    );
    
    $jtype   = array('INNER','INNER'); 

    $orderby = array(" a.created_at DESC ");

    $data = array(
        'where'=>$where,
        'joinTables'=>$tables,
        'fields'=>$fields,
        'joinFields'=>$jfields,
        'joinTypes'=>$jtype,
        'orderBy'=>$orderby,
        'limit'=>$limit
    );
    
    $transDetails  = $agencyClinicPointObj->getAllRecords($data);
    $recordsTotal = $agencyClinicPointObj->getAllCount($data); 

    if ($transDetails && count($transDetails)>0){
        foreach ($transDetails as $trans){
            
            $clinic_name = $trans->clinic_name ?? '-';
            
            $admin_name = '-';
            if(!empty($trans->admin_id) && !empty($trans->admin_fname)){
                 $admin_name = ($trans->admin_fname) . ' ' . ($trans->admin_lname);
            }

            $response[] = array(
                $clinic_name,
                $trans->points,
                "$ ".$trans->amount,
                $trans->type,
                $trans->description,
                $admin_name,
                $trans->created_at
            );
        }
        $result = array('recordsFiltered'=>$recordsTotal,'recordsTotal'=>$recordsTotal,'data'=>$response);
    } else {
        $result = array('recordsFiltered'=>0,'recordsTotal'=>0,'data'=>array());
    }
    echo json_encode($result);
    exit;
}

// Get all clinics for dropdown
$clinicObj = new clinic();
$clinicFields = array('clinic_id', 'clinic_name');
$clinicArg = array("fields" => $clinicFields);
$clinicData = $clinicObj->getAllRecords($clinicArg);

// Include Template 
include_once('../libs/routs.php');
?>
