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

$loyaltyObj   = new loyalty_action();
$dependantObj = new dependant();

$status = $_REQUEST['status'] ?? 'Allocated';

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

    $records = $_REQUEST['length'];
    $start=0;
    if(isset($_GET['start']) && $_GET['start']!='0'){
        $page = $_GET['start'];
    }
    $start=($page-1)*$limit;
    $limit = array('start'=>$_GET['start'],'record'=>$records);

    $where = "1=1 AND l.loyalty_action_status = '".$status."'";
    

    $tables  = array('tbl_dependant d');
    $fields = array('l.loyalty_action_id,d.dependant_id, d.dependant_fname, d.dependant_lname, SUM(l.loyalty_action_rpoints) AS total_points, l.loyalty_action_status');
    $jfields = array('d.dependant_id = l.loyalty_action_dependant_id');
    $jtype   = array('INNER');
    $groupby = array('l.loyalty_action_dependant_id');
    $orderby = array('total_points DESC');

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

    //$data['debug'] = true;
    $loyaltyDetail = $loyaltyObj->getAllRecords($data);
    $data['countfields'] = array('COUNT(DISTINCT l.loyalty_action_dependant_id) AS total');

    unset($data['fields']);
    unset($data['groupBy']);
    unset($data['orderBy']);
    unset($data['limit']);
    // $data['debug'] =true;
    $recordsTotal  = $loyaltyObj->getAllCount($data);

    $response = array();
    if($loyaltyDetail && count($loyaltyDetail) > 0){
        foreach($loyaltyDetail as $rec){
            $patientName = w::d($rec->dependant_fname).' '.w::d($rec->dependant_lname);
            $status = $rec->loyalty_action_status;
            $points = number_format($rec->total_points);
            $response[] = array(
                $patientName,
                $status,
                $points,
                "<a href='loyaltyActionlist.php?dependantId=".$rec->dependant_id."' target='_blank'>Action List</a>"
            );
        }
    }else {
        $result = array('recordsFiltered'=>0,'recordsTotal'=>0,'data'=>array());
    }

    $result = array(
        'recordsFiltered' => $recordsTotal,
        'recordsTotal' => $recordsTotal,
        'data' => $response
    );

    echo json_encode($result);
    exit;
}

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