<div class="breadcrumb">
    <!-- <h1>Dependant</h1> -->
    <h1>Loyalty Action</h1>
    <ul>
        <li><a href="<?php echo SITE_URL.ADMIN_DIR ?>">Dashboard</a></li>
        <!-- <li>Dependant list</li> -->
        <li>Loyalty Action list</li>
    </ul>
</div>
<div class="separator-breadcrumb border-top"></div>


<form action="" method="post">
<div class="row">
    <div class="col-lg-12 col-md-12">
        <div class="card mb-5">
            <div class="card-body">
            <div class="row row-xs">

                <div class="col-md-2 mt-3 mt-md-0" id="div_dependant_id">
                    <label for="dependant_id">Xcare Patient Id</label>
                    <input type="text" class="form-control" name="dependant_id" id="dependant_id" />
                </div>

                <div class="col-md-2 mt-3 mt-md-0" id="div_dependant_firstname">
                    <label for="dependant_firstname">First Name</label>
                    <input type="text" class="form-control" name="dependant_firstname" id="dependant_firstname" />
                </div>

                <div class="col-md-2 mt-3 mt-md-0" id="div_dependant_lastname">
                    <label for="dependant_lastname">Last Name</label>
                    <input type="text" class="form-control" name="dependant_lastname" id="dependant_lastname" />
                </div>

                <div class="col-md-2 mt-3 mt-md-0" id="div_loyalty_member">
                    <label for="point_category">Point Category</label>
                    <select name="point_category" id="point_category" class="form-control">
                        <option value="">Select</option>
                        <?php
                        $catObj = new pointcategory();
                        $categories = $catObj->getAllRecords([]);
                        if($categories){
                            foreach($categories as $cat){
                                echo "<option value='".$cat->pointcategory_title."'>".$cat->pointcategory_title."</option>";
                            }
                        }
                        ?>
                    </select>
                </div>

                <div class="col-md-2 mt-3 mt-md-0" id="div_clinic_id">
                    <label for="clinic_id">Clinic</label>
                    <select class="form-control" id="clinic_id" name="clinic_id" multiple>
                        <option value="">Select Clinic</option>
                        <?php
                            $loyalty_actionObj = new loyalty_action();
                            $fields =array('DISTINCT loyalty_action_clinic_id as clinicId','c.clinic_name','c.clinic_id');
                            $tables = array('tbl_clinic c');
                            $jfields = array('c.clinic_id = l.loyalty_action_clinic_id');
                            $jtype   = array("INNER"); 
                            
                            $arg =array('fields'=>$fields,'joinTables' =>$tables,'joinFields' =>$jfields,'joinTypes' => $jtype);
                        
                            $clinicdata = $loyalty_actionObj->getAllRecords($arg);
                            foreach ($clinicdata as $ckey => $clinic_value) { 
                            ?>
                            <option value="<?php echo $clinic_value->clinic_id; ?>"><?php echo $clinic_value->clinic_name; ?></option>
                        <?php } ?>
                    </select>
                </div>

                <!-- ✅ New Appointment Dropdown -->
                <div class="col-md-2 mt-3 mt-md-0" id="div_appointment_status">
                    <label for="appointment_status">Appointment</label>
                    <select name="appointment_status" id="appointment_status" class="form-control">
                        <option value="">Select</option>
                        <option value="Completed">Completed</option>
                    </select>
                </div>

                <div class="col-md-2 mt-3 mt-md-0" id="div_month">
                    <label for="month">Month</label>
                    <select name="month[]" id="month" class="form-control" multiple>
                        <option value="">Select Month</option>
                        <?php
                            $months_list = [
                                '01' => 'January', '02' => 'February', '03' => 'March', '04' => 'April', 
                                '05' => 'May', '06' => 'June', '07' => 'July', '08' => 'August', 
                                '09' => 'September', '10' => 'October', '11' => 'November', '12' => 'December'
                            ];
                            
                            foreach ($months_list as $month_num => $month_name) {
                                echo "<option value='".$month_num."'>".$month_name."</option>";
                            }
                        ?>
                    </select>
                </div>

                <div class="col-md-2 mt-3 mt-md-0" id="div_year">
                    <label for="year">Year</label>
                    <select name="year" id="year" class="form-control">
                        <option value="">Select year</option>
                        <?php
                        $currentYear = date('Y');
                        for ($i = 0; $i < 3; $i++) {
                            $y = $currentYear - $i;
                            echo "<option value='$y'>$y</option>";
                        }
                        ?>
                    </select>
                </div>

                <div class="col-md-2 mt-3 mt-md-0"  id="div_source">
                        <label for="source">Source</label>
                        <select class="form-control" id="source" name="source">
                            <option value="">Select Source</option>
                            <option value="seo">Seo</option>
                            <option value="onlinescheduling">OnlineScheduling</option>
                            <option value="gmb">gmb</option>
                            <option value="meta-ads">meta-ads</option>
                            <option value="google-ads">google-ads</option>
                            <option value="xcare-loyalty">xcare-loyalty</option>
                        </select>
                </div>

                <div class="col-md-2 mt-3 mt-md-0">
                    <label for="">&nbsp;</label>
                    <button type="submit" name="submit" class="btn btn-primary btn-block">Search</button>
                </div>

                <div class="col-md-2 mt-3 mt-md-0">
                    <label for="">&nbsp;</label>
                    <button type="reset" name="reset" class="btn btn-primary btn-block" onClick="window.location.reload()">Reset</button>
                </div>

                <div class="col-md-2 mt-3 mt-md-0">
                    <label for="">&nbsp;</label>
                    <button type="button" class="btn btn-success btn-block" id="btnExport" onclick="exportLoyaltyData()">Export</button>
                </div>

                </div>

            </div>
        </div>
    </div>
</div>
</form>


<div class="widget-body">
    <div class="portlet-body">
                        
    <?php echo (isset($successMsg) && $successMsg!='') ? "<div class='alert alert-success'><button data-dismiss='alert' class='close' type='button'>×</button>".base64_decode($successMsg)."</div>" : '' ; ?>
    <?php echo (isset($failedMsg) && $failedMsg!='') ? "<div class='alert alert-danger'><button data-dismiss='alert' class='close' type='button'>×</button>".base64_decode($failedMsg)."</div>" : '' ?>
   
    <div id="status_msg" style="display: none;"><div class="alert alert-success"><button data-dismiss='alert' class='close' type='button'>×</button>&nbsp;</div></div>
    <div id="alert_msg" style="display: none;"><div class="alert alert-danger"><button data-dismiss='alert' class='close' type='button'>×</button>&nbsp;</div></div>

    </div>
</div>


<div class="row mb-4">
    <div class="col-md-12 mb-4">
        <div class="card text-left">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="loyaltyList" class="display table table-striped table-bordered" style="width:100%">
                        <thead>
                            <tr>
                                <th>Patient Details</th>
                                <th>Campaign / Clinic / Appointment</th>
                                <th>Points Info</th>
                                <th>Status / Action</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="./assets/js/jquery.multiselect.js"></script>
<link rel="stylesheet" href="./assets/styles/css/jquery.multiselect.css">
<script type="application/javascript">
    $('#clinic_id').multiselect({
            columns: 1,
            placeholder: 'Select Clinic',
            search: true,
            //selectAll: true
    });

    $('#month').multiselect({
        placeholder: "Select Month",
        allowClear: true,
        width: '100%'
    });

    function exportLoyaltyData() {
        var point_category = $("#point_category").val();
        var clinic_id      = $("#clinic_id").val();
        var month          = $("#month").val();
        var year           = $("#year").val();
        var appointment_status = $("#appointment_status").val();
        
        // Validate all three fields
        // if (point_category === "" || clinic_id === "" || month === "") {
        //     alert("Please select Point Category, Clinic, and Month before exporting.");
        //     return false;
        // }

        if (!clinic_id || clinic_id.length == 0) {
            alert("Please select Clinic before exporting.");
            return false;
        }
        
        // Build export URL
        // var exportUrl = "loyaltyActionlist.php?act=export"
        //                 + "&point_category=" + encodeURIComponent(point_category)
        //                 + "&clinic_id=" + encodeURIComponent(clinic_id)
        //                 + "&month=" + encodeURIComponent(month)
        //                 + "&appointment_status=" + encodeURIComponent(appointment_status);


        var exportUrl = "loyaltyActionlist.php?act=export"
                    + "&clinic_id=" + encodeURIComponent(clinic_id);

        if (point_category) {
            exportUrl += "&point_category=" + encodeURIComponent(point_category);
        }

        if (month && month.length > 0) {
            exportUrl += "&month=" + encodeURIComponent(month.join(",")); 
        }

        if (year) {
            exportUrl += "&year=" + encodeURIComponent(year);
        }

        if (appointment_status) {
            exportUrl += "&appointment_status=" + encodeURIComponent(appointment_status);
        }

        // Trigger download
        window.location.href = exportUrl;
    }
$(document).ready(function() {
    <?php 
        if(isset($_GET['dependantId']) && $_GET['dependantId']!=""){?>
        $('#loyaltyList').DataTable({ 
            "ajax": "loyaltyActionlist.php?act=load&xcare_patient_id="+<?php echo $_GET['dependantId'] ?>,
            "processing": true,
            "serverSide": true,
            "pageLength": 25,
            "aaSorting": [],
            "language": {
                "processing" : "<div class='loader-bubble loader-bubble-primary m-5'></div>",
                "sEmptyTable" :  "No records found."
            }
        });
    <?php    }
    ?>
    

    $("form").on("submit", function(e) {
        e.preventDefault();

        var dependant_id       = $("#dependant_id").val();
        var dependant_firstname= $("#dependant_firstname").val();
        var dependant_lastname = $("#dependant_lastname").val();
        var point_category     = $("#point_category").val();
        var clinic_id          = $("#clinic_id").val();
        var month              = $("#month").val();
        var year               = $("#year").val();
        var appointment_status = $("#appointment_status").val();
        var source             = $("#source").val();

        // var months = $("#month").val();  // array
        // var month_param = "";

        // if (months && months.length > 0) {
        //     month_param = months.join(",");   // "01,02,05"
        // }

        $('#loyaltyList').DataTable().destroy();
        $('#loyaltyList').DataTable({ 
            "ajax": "loyaltyActionlist.php?act=load"
                    +"&xcare_patient_id="+dependant_id
                    +"&firstname="+dependant_firstname
                    +"&lastname="+dependant_lastname
                    +"&point_category="+point_category
                    +"&clinic_id="+clinic_id
                    +"&month="+month
                    +"&year="+year
                    +"&appointment_status="+appointment_status
                    +"&source="+source,
            "processing": true,
            "serverSide": true,
            "pageLength": 25,
            "aaSorting": [],
            "language": {
                "processing" : "<div class='loader-bubble loader-bubble-primary m-5'></div>",
                "sEmptyTable" :  "No records found."
            }
        });
    });
});
</script>
