<?php //include('pdf_header_reverse.php');
include('includes/config/config.php');
include('includes/functions.php');
//include('pop_up_top.php');
header("Content-type:application/octet-stream");

header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=chronic_medication_medicine_report.xls");
header("Pragma: no-cache");
header("Expires: 0");

$chronic_illness_id = $_REQUEST['chronic_illness_p'];
if (count($chronic_illness_id) != 1) {
    foreach (array_keys($chronic_illness_id, 'ALL') as $key) {
        unset($chronic_illness_id[$key]);
    }
}
if (count($chronic_illness_id) == 1 && $chronic_illness_id[0] == 'ALL') {
    $chronic_illness_str = "";
} else {

    $chronic_illness_str = 'and diseases in (';
    foreach ($chronic_illness_id as $key => $chronic) {
        if ($chronic != 'ALL') {
            $chronic_illness_str .= $chronic . ",";
        }
    }

    $chronic_illness_str .= "0)";
}

// echo("chronics ".$chronic_illness_str);
$start = date('d-m-Y', strtotime($_POST['opdDate1']));
$end = date('d-m-Y', strtotime($_POST['opdDate2']));
$from_date1 = date('Y-m-d', strtotime($_POST['opdDate1']));
$from_date = date('d-m-Y', strtotime($from_date1));
$from_date2 = date('Y-m-d', strtotime($_POST['opdDate2']));
$to_date = date('d-m-Y', strtotime($from_date2));
?>
<link href="includes/css-js/admin.css" rel="stylesheet" type="text/css" />
<style>
    @page {
        margin: 15px;
    }

    .btn {
        background-color: #4CAF50;
        border-radius: 5%;
        /* Green */
        border: none;
        color: white;
        padding: 5px 8px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 12px;
        margin: 4px 2px;
        cursor: pointer;
    }

    @media print {
        #printPageButton {
            display: none;
        }
    }
</style>

<body>
    <table width="100%">
        <tr>

            <td style="font-size: 15px;"><strong style="margin-left: 400px">New Chronically ILL Patient Report
                </strong></td>

        </tr>
        <tr>
            <td align="left" style="font-size: 12px"><strong>From Date:
                    <?php echo date("d-M-Y", strtotime($from_date)); ?>&nbsp;&nbsp;&nbsp;To Date:
                    <?php echo date("d-M-Y", strtotime($to_date)); ?>
                </strong></td>
            <td align="right" style="font-size: 15px"><button align="center" id="printPageButton" class="btn btn-success" onClick="window.print();">Print</button></td>
        </tr>

    </table>
    <br>
    <table border="1" width="100%" cellspacing="0">
        <strong>
            <tr bgcolor="#eeeeee">
                <td align="left" width="2%">Sr.</td>
                <td align="left" width="3%">Chronic Illness</td>
                <td align="left" width="3%">Diagnosis date</td>
                <td align="left" width="2%">Patient Name</td>

                <td valign="top" align="left" width="3%">Emp. No.</td>
                <td valign="top" align="left" width="3%">Plant</td>
                <td valign="top" align="left" width="2%">Age</td>
                <td valign="top" align="left" width="2%">Sex</td>

                <td valign="top" align="left" width="5%">Mobile No.</td>
                <td valign="top" align="left" width="3%">Employer</td>
                <td valign="top" align="left" width="5%">Designation</td>
                <td valign="top" align="left" width="3%">Division</td>
                <td valign="top" align="left" width="3%">Department</td>
                <td valign="top" align="left" width="3%">Section</td>

                <!-- <td valign="top" align="left" width="3%">Medicine</td>
                <td valign="top" align="left" width="3%">Frequency</td>
                <td valign="top" align="left" width="3%">Timing</td>
                <td valign="top" align="left" width="5%">Admin.Route</td>

                <td valign="top" align="left" width="3%">Duration</td> -->


            </tr>

            <?php

            $app_ids = array();
            $count = 1;
            $chronic_patient_arr = array();
            $patient_chronics = array();

            $q_pres = "SELECT a.*, emp.*  FROM prescription_master a INNER JOIN patient_master emp ON a.emp_id = emp.id WHERE (DATE(a.diagnosis_date) BETWEEN STR_TO_DATE('" . $start . "','%d-%m-%Y') AND STR_TO_DATE('" . $end . "','%d-%m-%Y') OR a.diagnosis_date IS NULL) AND a.ohc_type_id = '" . $_SESSION['current_ohcttype'] . "' " . $chronic_illness_str;

            // error_log($sql);

            //    echo ($q_pres);
            $result_pres = mysqli_query($conn, $q_pres);
            while ($prescription_r = mysqli_fetch_assoc($result_pres)) {
                if (!in_array($prescription_r["emp_id"], $chronic_patient_arr)) {
                    array_push($chronic_patient_arr, $prescription_r["emp_id"]);
                }
                // echo $prescription["emp_id"];

                //     if ($prescription['diagnosis_date'] != null && $prescription['diagnosis_date'] != '' && $prescription['diagnosis_date'] != '1970-01-01' && $prescription['diagnosis_date'] != '0000-00-00') {

                //         $date = DateTime::createFromFormat('Y-m-d', $prescription['diagnosis_date']);
                //         // Format the date in "d/m/Y" format
                //         $newDateFormat = $date->format('d/m/Y');
                //         $diagnosis_date = $newDateFormat;
                // } else {
                //         $diagnosis_date = "Not Present";
                // }

                $patient_chronics[$prescription_r["emp_id"]] .= getTableFieldValue('abnormality', 'abnormality_name', 'abnormality_id', $prescription_r['diseases']) . ',';
                $patient_diagnosis[$prescription_r["emp_id"]] .= $prescription_r['diagnosis_date'] . ',';
            }



            foreach ($chronic_patient_arr as $key => $emp) {

                $q_emp = "SELECT  *  FROM `view_patient_master` where id='" . $emp . "' ";

                // error_log($sql);

                //    echo ($q_pres);
                $result_emp = mysqli_query($conn, $q_emp);
                while ($prescription = mysqli_fetch_assoc($result_emp)) {
                    array_unique($patient_diagnosis)

            ?>
                    <tr>
                        <td><?php echo  $count; ?></td>

                        <td>
                            <?php
                            $chronic_illnesses = explode(',', rtrim($patient_chronics[$emp], ','));
                            $unique_illnesses = array_unique($chronic_illnesses);

                            foreach ($unique_illnesses as $illness) {
                                echo $illness . "<br>";
                            }
                            ?>
                        </td>
                        <td>
                            <?php
                            $diagnosis_dates = array_unique(explode(',', rtrim($patient_diagnosis[$emp], ',')));

                            foreach ($diagnosis_dates as $date) {
                                if (!empty($date) && $date != '0000-00-00') {
                                    echo date('d-m-Y', strtotime($date)) . "<br>";
                                } else {
                                    echo "NA<br>";
                                }
                            }
                            ?>
                        </td>

                        <td><?php echo $prescription['patient_name']; ?></td>
                        <td><?php echo $prescription['emp_code']; ?></td>
                        <td><?php echo getTableFieldValue('plant_master', 'plant_name', 'plant_id', $prescription['plant_id']) ?></td>
                        <td><?php $from = new DateTime($prescription['dob']);
                            $to   = new DateTime('today');
                            echo $from->diff($to)->y;
                            ?></td>
                        <td><?php if ($prescription['gender'] == 'M') {
                                echo 'Male';
                            } else {
                                echo 'Female';
                            } ?></td>
                        <td><?php echo $prescription['primary_phone'] ?></td>
                        <td><?php echo getFieldFromTable('employer_contractor_name', 'employer_contractor', 'id', $prescription['employer_contractor_id']) ?>
                        </td>
                        <td><?php echo getTableFieldValue('designation', 'designation_name', $prescription['designation_id'], 'designation_id',) ?>
                        </td>
                        <td><?php echo getTableFieldValue('bussiness_unit', 'bu_name', $prescription['bu_id'], 'bu_id') ?></td>

                        <td><?php echo getTableFieldValue('department', 'dept_name', $prescription['dept_id'], 'dept_id') ?></td>

                        <td><?php echo getTableFieldValue('section', 'section_name', $prescription['section_id'], 'section_id') ?>
                        </td>
                        <!-- <td><?= getTableFieldValue('tbl_items', 'item_name', 'item_id', $prescription['medicine_name']) ?></td>
                <td><?= getTableFieldValue('medicine_frequency', 'medicine_frequency', 'frequency_id', $prescription['medicine_frequency']); ?></td>
                 <td><?= getTableFieldValue('medicine_timings', 'medicine_timing', 'timing_id', $prescription['medicine_timing']) ?></td>
                 <td><?= getTableFieldValue('dosage_category', 'dosage_category', 'dosage_category_id', $prescription['admin_route']) ?></td>
                 <td><?= $prescription['duration'] ?></td> -->


                    </tr>
            <?php
                    $count++;
                }
            }



            ?>

    </table>
</body>