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

$loyaltyObj   = new loyalty_action();
$dependantObj = new dependant();
$patientObj   = new patient();
$clinicObj    = new clinic();
$appointmentObj = new appointment();

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

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

    $where = " 1=1 ";

    if(isset($_REQUEST['xcare_patient_id']) && $_REQUEST['xcare_patient_id'] != ''){
        $where .= " AND d.dependant_id = '".($_REQUEST['xcare_patient_id'])."' ";
    }

    if(isset($_REQUEST['firstname']) && $_REQUEST['firstname'] != ''){
        $where .= " AND d.dependant_fname LIKE '%".w::e($_REQUEST['firstname'])."%' ";
    }

    if(isset($_REQUEST['lastname']) && $_REQUEST['lastname'] != ''){
        $where .= " AND d.dependant_lname LIKE '%".w::e($_REQUEST['lastname'])."%' ";
    }

    if(isset($_REQUEST['point_category']) && $_REQUEST['point_category'] != ''){
        $where .= " AND pc.pointcategory_title = '".($_REQUEST['point_category'])."' ";
    }

    if(isset($_REQUEST['clinic_id']) && $_REQUEST['clinic_id'] != ''){
        $where .= " AND l.loyalty_action_clinic_id IN (".$_REQUEST['clinic_id'].") ";
    }

    if(isset($_REQUEST['source']) && $_REQUEST['source'] != ''){
        $where .= " AND a.appointment_source = '".($_REQUEST['source'])."' ";
    }
    
    // if(isset($_REQUEST['month']) && $_REQUEST['month'] != ''){
        
    //     $month_num = $_REQUEST['month'];
    //     $current_year = date('Y');
    //     $month_year = $current_year . '-' . $month_num;

    //     $start_date = $month_year . '-01';
    //     $end_date   = date('Y-m-t', strtotime($start_date));
        
    //     $where .= " AND DATE(l.loyalty_action_created_at) BETWEEN '".($start_date)."' AND '".($end_date)."' ";
    // }


    if (isset($_REQUEST['month']) && $_REQUEST['month'] != '') {

        $months = explode(",", $_REQUEST['month']);

        $current_year = (isset($_REQUEST['year']) && $_REQUEST['year'] != '') ? $_REQUEST['year'] : date('Y');
        $month_conditions = [];

        foreach ($months as $month_num) {

            $month_num = trim($month_num);

            if ($month_num == "") continue;

            $start_date = $current_year . '-' . $month_num . '-01';
            $end_date   = date('Y-m-t', strtotime($start_date));

            $month_conditions[] = "(DATE(l.loyalty_action_created_at) BETWEEN '$start_date' AND '$end_date')";
        }

        if (count($month_conditions) > 0) {
            $where .= " AND (" . implode(" OR ", $month_conditions) . ") ";
        }
    } else if (isset($_REQUEST['year']) && $_REQUEST['year'] != '') {
        $where .= " AND YEAR(l.loyalty_action_created_at) = '" . $_REQUEST['year'] . "' ";
    }

    if (!empty($_REQUEST['appointment_status']) && $_REQUEST['appointment_status'] == 'Completed') {
        $where .= " AND a.appointment_status = 'completed' ";
    }
    $tables  = array('tbl_dependant d','tbl_pointmaster pm','tbl_pointcategory pc','tbl_clinic c','tbl_appointment a');
    $jfields = array(
        'd.dependant_id = l.loyalty_action_dependant_id',
        'pm.pointmaster_id = l.loyalty_action_point_id',
        'pc.pointcategory_id = pm.pointmaster_category_id',
        'c.clinic_id = l.loyalty_action_clinic_id',
        'a.appointment_id = l.loyalty_action_appointment_id'
    );
    $jtype   = array('INNER','INNER','LEFT','LEFT','LEFT');

    $orderby = array(" l.loyalty_action_id DESC ");

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

    $actionDetails = $loyaltyObj->getAllRecords($data);
    $recordsTotal  = $loyaltyObj->getAllCount($data);

    if ($actionDetails && count($actionDetails)>0){
        foreach ($actionDetails as $action){

            $patientInfo = "<b>ID:</b> ".$action->dependant_id."<br/>
                            <b>Name:</b> ".w::d($action->dependant_fname)." ".w::d($action->dependant_lname)."<br/>
                            <b>Phone:</b> ".w::d($action->dependant_phone)."<br/>
                            <b>Email:</b> ".w::d($action->dependant_email_address);

            $campaignInfo = "<b>Campaign:</b> ".$action->pointmaster_title."<br/>
            <b>Category:</b> ".$action->pointcategory_title."<br/>";
            if(!empty($action->clinic_id)){
                $campaignInfo .= "<b>Clinic:</b> ".$action->clinic_name."<br/>";
            }
            if(!empty($action->appointment_id)){
                $campaignInfo .= "<b>Appointment:</b> Date: ".$action->appointment_date." | Time: ".$action->appointment_time."<br/>
                <b>Source:</b> <b>".$action->appointment_source."</b><br/>";
            }

            $pointsInfo = "<b>Points:</b> ".$action->loyalty_action_rpoints."<br/>
                           <b>Bonus Points:</b> ".$action->loyalty_action_bonus_id."<br/>
                           <b>Description:</b> ".w::d($action->loyalty_action_description);

            $statusInfo = "<b>Status:</b> ".$action->loyalty_action_status."<br/>
                           <b>Action:</b> ".$action->loyalty_action_action."<br/>
                           <b>Action Date:</b> ".$action->loyalty_action_created_at;

            $response[] = array(
                $patientInfo,
                $campaignInfo,
                $pointsInfo,
                $statusInfo
            );
        }

        $result = array('recordsFiltered'=>$recordsTotal,'recordsTotal'=>$recordsTotal,'data'=>$response);
    } else {
        $result = array('recordsFiltered'=>0,'recordsTotal'=>0,'data'=>array());
    }

    echo json_encode($result);
    exit;
}

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

    if (!empty($_REQUEST['point_category'])) {

        if ($where != "") {
           $where .= " AND ";
        }

        $where .= " pc.pointcategory_title = '" . ($_REQUEST['point_category']) . "' ";
    }

    if (!empty($_REQUEST['clinic_id'])) {

        if ($where != "") {
            $where .= " AND ";
        }
        $where .= "  l.loyalty_action_clinic_id IN (".$_REQUEST['clinic_id'].") ";
    }
    // $clinicObj = new clinic();
    // $clinic =$clinicObj->fromId($_REQUEST['clinic_id']);

    // if (!empty($_REQUEST['month'])) {
    //     $month_num = $_REQUEST['month'];
    //     $current_year = date('Y');
    //     $month_year = $current_year . '-' . $month_num;

    //     $start_date = $month_year . '-01';
    //     $end_date   = date('Y-m-t', strtotime($start_date));

    //     $where .= " AND DATE(l.loyalty_action_created_at) BETWEEN '" . ($start_date) . "' AND '" . ($end_date) . "' ";
    // }

    if (isset($_REQUEST['month']) && $_REQUEST['month'] != '') {

        if ($where != "") {
           $where .= " AND ";
        }

        $months = explode(",", $_REQUEST['month']);

        $current_year = (isset($_REQUEST['year']) && $_REQUEST['year'] != '') ? $_REQUEST['year'] : date('Y');

        $month_conditions = [];

        foreach ($months as $month_num) {

            $month_num = trim($month_num);
            if ($month_num == "") continue;

            $month_num = str_pad($month_num, 2, '0', STR_PAD_LEFT);

            $start_date = $current_year . '-' . $month_num . '-01';
            $end_date   = date('Y-m-t', strtotime($start_date));

            $month_conditions[] = " (DATE(l.loyalty_action_created_at) BETWEEN '$start_date' AND '$end_date') ";
        }

        if (count($month_conditions) > 0) {
            $where .= " (" . implode(" OR ", $month_conditions) . ") ";
        }
    } else if (isset($_REQUEST['year']) && $_REQUEST['year'] != '') {
        if ($where != "") {
            $where .= " AND ";
        }
        $where .= " YEAR(l.loyalty_action_created_at) = '" . $_REQUEST['year'] . "' ";
    }


    if (!empty($_REQUEST['appointment_status']) && $_REQUEST['appointment_status'] == 'Completed') {
        $where .= " AND a.appointment_status = 'completed' ";
    }
    $tables  = array('tbl_dependant d', 'tbl_pointmaster pm', 'tbl_pointcategory pc', 'tbl_clinic c', 'tbl_appointment a');
    $jfields = array(
        'd.dependant_id = l.loyalty_action_dependant_id',
        'pm.pointmaster_id = l.loyalty_action_point_id',
        'pc.pointcategory_id = pm.pointmaster_category_id',
        'c.clinic_id = l.loyalty_action_clinic_id',
        'a.appointment_id = l.loyalty_action_appointment_id'
    );
    $jtype   = array('INNER', 'INNER', 'LEFT', 'LEFT', 'LEFT');
    $orderby = array(" l.loyalty_action_id DESC ");

    $data = array(
        'where'      => $where,
        'joinTables' => $tables,
        'joinFields' => $jfields,
        'joinTypes'  => $jtype,
        'orderBy'    => $orderby
    );
    // $data['debug'] =true;
    $actionDetails = $loyaltyObj->getAllRecords($data);
    if ($_REQUEST['act'] == 'export') {

        if (!$actionDetails || count($actionDetails) == 0) {
            die("No records found for export.");
        }

        $filename = "Export_".$month_num."_".$current_year.".csv";
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment; filename=\"$filename\"");

        $output = fopen("php://output", "w");

        // CSV headers
        fputcsv($output, ['Patient ID', 'Patient Name', 'Phone', 'Email', 'Campaign', 'Category', 'Clinic', 'Appointment','Source' ,'Points', 'Description', 'Status', 'Action', 'Date']);

        foreach ($actionDetails as $action) {
            $row = [
                $action->dependant_id,
                w::d($action->dependant_fname)." ".w::d($action->dependant_lname),
                w::d($action->dependant_phone),
                w::d($action->dependant_email_address),
                $action->pointmaster_title,
                $action->pointcategory_title,
                $action->clinic_name ?? '',
                !empty($action->appointment_id)
                    ? ($action->appointment_date . ' ' . $action->appointment_time)
                    : '',
                $action->appointment_source,    
                $action->loyalty_action_rpoints,
                $action->loyalty_action_description,
                $action->loyalty_action_status,
                $action->loyalty_action_action,
                $action->loyalty_action_created_at
            ];
            fputcsv($output, $row);
        }

        fclose($output);
        exit;
    }
}

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