<?
include('includes/config/config.php');
include('includes/functions.php');

header("Content-type:application/octet-stream");

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

?>
<?php
$date = date('Y-m-d', strtotime($_POST['startDate1']));

error_log("date:::" . $date);

$shiftId = $_REQUEST['shift'];

$ZeroAllowed = "N";
error_log("key val before"  . $ZeroAllowed);
$ZeroAllowedKey = getConfigKey("ZERO_QUANTITY_ALLOWED");
error_log("key val "  . $ZeroAllowedKey);
if ($ZeroAllowedKey == "TRUE") {
    $ZeroAllowed = "Y";
}
error_log("key val after "  . $ZeroAllowed);

function getShiftDetails($shiftId, $date, $current_status, $p, $is_shift)
{
    $sql_shift = "select ssd.*,ss.* from shift_status_details ssd left join shift_status ss on ssd.shift_id = ss.shift_status_id where ssd.ohc_location_id='" . $_SESSION['current_ohcttype'] . "' and ssd.shift_id = '" . $shiftId . "' and ssd.current_status = '" . $current_status . "' and ssd.record_date = '" . $date . "' and is_shift = '" . $is_shift . "'";

    error_log("getShiftDetails:" . $sql_shift);
    $result_shift = mysqli_query($GLOBALS['conn'],$sql_shift);
    while ($row_shift = mysqli_fetch_assoc($result_shift)) {
        if ($p == "start") {
            return $row_shift['start_date_time'];
        }
        if ($p == "end") {
            return $row_shift['end_date_time'];
        }
        if ($p == "id") {
            return $row_shift['shift_details_id'];
        }
        if ($p == "name") {
            return $row_shift['status_name'];
        }
    }
}

$current_status = 'C';
$getValue = "start";
$getValue2 = "end";
$shift_detail_id = "id";
$is_shift = 'Y';
$shift_name = "name";

$shiftName = getShiftDetails($shiftId, $date, $current_status, $shift_name, $is_shift);

$shift_start_time = getShiftDetails($shiftId, $date, $current_status, $getValue, $is_shift);

$shift_end_time = getShiftDetails($shiftId, $date, $current_status, $getValue2, $is_shift);

$shift_details_id = getShiftDetails($shiftId, $date, $current_status, $shift_detail_id, $is_shift);

// $prev_shift_id = ceil($shift_details_id - 1);

$prev_shift_id_sql = "select * from shift_status_details where ohc_location_id='" . $_SESSION['current_ohcttype'] . "' and current_status = 'C' and shift_details_id < '" . $shift_details_id . "' order by shift_details_id DESC ";
$prev_shift_id_sql_result = mysqli_query($conn,$conn,$prev_shift_id_sql);
$prev_shift_id_sql_row = mysqli_fetch_assoc($prev_shift_id_sql_result);
$prev_shift_id = $prev_shift_id_sql_row['shift_details_id'];

error_log("prev_shift_id_sql: " . $prev_shift_id_sql);

error_log("shift start time::" . $shift_start_time);
error_log("shift end time::" . $shift_end_time);
error_log("shift details id::" . $shift_details_id);
error_log("prev shift id::" . $prev_shift_id);
error_log("shift name::" . $shiftName);
error_log("shift id::" . $shiftId);

$prev_shift_start_time = '';
$prev_shift_end_time = '';
$shift = '';

$sql_prev = "select * from shift_status_details where shift_details_id='" . $prev_shift_id . "'";
$result_prev = mysqli_query($conn,$conn,$sql_prev);

while ($row_prev = mysqli_fetch_assoc($result_prev)) {
    $prev_shift_start_time = $row_prev['start_date_time'];
    $prev_shift_end_time = $row_prev['end_date_time'];
    $shift = $row_prev['shift_id'];
}

error_log("prev shift start time::" . $prev_shift_start_time);
error_log("prev shift end time::" . $prev_shift_end_time);
error_log("prev shift id::" . $shift);

$ohc = $_SESSION['current_ohcttype'];

?>


<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>
    <?php include('excel_ohc_header.php'); ?>
    <table width="100%">
        <tr>

            <td align="center" style="font-size: 15px"><strong>Daily Shift Wise Medicine Log Report</strong></td>

        </tr>
        <tr>
            <td align="left" style="font-size: 12px"><strong>For Date: <?php echo date("d-M-Y", strtotime($date)) . "  " . "Shift Name: " . $shiftName; ?></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 width="100%" border="1" cellspacing="0">
        <tr>
            <th width="1%" align="center">Sr</th>
            <th align="center" width="8%">Items</th>
            <th align="center" width="2%">Fresh</th>
            <th align="center" width="3%">Previous</th>
            <th align="center" width="2%">Total</th>
            <th align="center" width="40%">Consumption Details</th>
            <th align="center" width="2%">Total Consumed</th>
            <th align="center" width="2%">Balance</th>
        </tr>
        <?

        error_reporting(E_ERROR | E_PARSE);
        $count = 0;
        $data = "";
        $sql = "select cat_id from tbl_categories where cat_code not in ('CNC')  order by sequence asc";

        error_log("SSSSSSS$$$$$$$$$" . $sql);

        $result = mysqli_query($conn,$sql);

        $med_cat = array();

        function consume_details($item_id, $a, $date, $shift_start_time, $shift_end_time, $ohc)
        {
            $consume_detail = '';
            $issued_qty_total = 0;

            $sql_diect_issue_query = "SELECT ifnull(dd.issue_qty,0) as direct_issue FROM direct_medicine_issue_log_details dd LEFT JOIN direct_medicine_issue_log dm ON dd.issue_log_id = dm.issue_log_id WHERE item_id='$item_id' and date(date_of_issue) = '" . $date . "' and time(date_of_issue)>= time('$shift_start_time') and time(date_of_issue) <= ('$shift_end_time') and ohc_location_id = '" . $ohc . "'";

            error_log("sql_diect_issue_query: " . $sql_diect_issue_query);

            $result_sql_diect_issue_query = mysqli_query($GLOBALS['conn'],$sql_diect_issue_query);

            while ($row_result_sql_diect_issue_query = mysqli_fetch_array($result_sql_diect_issue_query)) {

                $consume_detail .= 'DIRECT ISSUE ' . ':' . $row_result_sql_diect_issue_query['direct_issue'] . ' : ';
                $issued_qty_total += $row_result_sql_diect_issue_query['direct_issue'];
            }

            error_log("issued_qty_total:::" . $issued_qty_total);

            $sql_opd_consumables = "SELECT ifnull(c.issued_qty,0) as consumable_issue,e.ticket_no FROM opd_consumables c LEFT JOIN employee_appointment e ON c.consume_id = e.appointment_id where medicine = '$item_id' and date(e.appointment_date) = '" . $date . "' and time(e.appointment_date)>= time('$shift_start_time') and time(e.appointment_date) <= time('$shift_end_time') and ohc_type_id = '" . $ohc . "'";

            error_log("sql_opd_consumables: " . $sql_opd_consumables);

            $result_sql_opd_consumables = mysqli_query($GLOBALS['conn'],$sql_opd_consumables);

            while ($row_result_sql_opd_consumables = mysqli_fetch_array($result_sql_opd_consumables)) {

                $consume_detail .= 'ID-' . $row_result_sql_opd_consumables['ticket_no'] . ':' . $row_result_sql_opd_consumables['consumable_issue'] . ' : ';
                $issued_qty_total += $row_result_sql_opd_consumables['consumable_issue'];
            }

            error_log("issued_qty_total_2:::" . $issued_qty_total);

            $sql_consume = "select a.appointment_id, (ifnull(a.issued_qty,0)+ifnull(c.issued_qty,0)) as total_issued,b.ticket_no from treatment a left join employee_appointment b on a.appointment_id = b.appointment_id left join detention_intake c on b.appointment_id = c.det_id  where item_id = '$item_id' and date(b.appointment_date) = '" . $date . "' and time(b.appointment_date)>= time('$shift_start_time') and time(b.appointment_date) <= time('$shift_end_time') and b.ohc_type_id = '" . $ohc . "'";

            error_log("cccccccons" . $sql_consume);

            $result_consume = mysqli_query($GLOBALS['conn'],$sql_consume);


            while ($row_consume = mysqli_fetch_array($result_consume)) {
                $consume_detail .= 'ID-' . $row_consume['ticket_no'] . ':' . $row_consume['total_issued'] . ' : ';

                $issued_qty_total += $row_consume['total_issued'];

                error_log("detaiilllllllllll" . $row_consume['total_issued']);
            }

            error_log("issued_qty_total_3:::" . $issued_qty_total);



            if ($a == 1) {
                return $consume_detail;
            } else {
                return $issued_qty_total;
            }
        }

        function freshReceivedItemBalance($item_id, $date, $ohc, $shift_start_time, $shift_end_time)
        {

            $received_qty_total = 0;

            $sql_fresh_received = "select ris.received_qty from received_issue_items ris left join received_master rm on ris.received_id = rm.received_id where ris.item_id='" . $item_id . "' and rm.received_date = '" . $date . "' and rm.ohc_location_id = '" . $ohc . "' and rm.last_modified>='$shift_start_time' and rm.last_modified<='$shift_end_time'";

            $result_fresh = mysqli_query($GLOBALS['conn'],$sql_fresh_received);

            while ($row_fresh = mysqli_fetch_assoc($result_fresh)) {
                $received_qty_total += $row_fresh['received_qty'];
            }

            error_log("fresh:::" . $sql_fresh_received);
            return $received_qty_total;
        }

        function prevDispensaryItemBalance($item_id, $ohc, $shift, $prev_shift_id)
        {
            $sql_prev_balance = "select stock_qty from item_stock_dispensary_shift_balance a left join shift_status_details b on a.shift_id = b.shift_id where a.item_id = '$item_id' and a.ohc_location_id = '$ohc' and a.shift_id='" . $shift . "' and b.shift_details_id  = '" . $prev_shift_id . "' and a.record_date = date(b.start_date_time) ";

            error_log("sql_prev_balance:::" . $sql_prev_balance);

            $result_sql_prev_balance = mysqli_query($GLOBALS['conn'],$sql_prev_balance);
            $row_prev_balance = mysqli_fetch_array($result_sql_prev_balance);

            if ($row_prev_balance == 0) {
                return 0;
            } else {
                return $row_prev_balance['stock_qty'];
            }
        }

        function total_qty($fresh, $prev)
        {
            $total = $fresh + $prev;

            return $total;
        }

        function balance($total_balance, $total_consumed)
        {
            error_log("balancesjfbbf :::" . $total_balance . " - " . $total_consumed);
            $b = $total_balance - $total_consumed;
            return $b;
        }

        while ($row_m = mysqli_fetch_array($result)) {

            array_push($med_cat, $row_m['cat_id']);
        }

        foreach ($med_cat as $i => $value) {

            $newCat = true;

            $query = "select item_id, item_name from tbl_items  where cat='$value' and status = '1' group by item_id";

            error_log("###########QQQQQQQQ" . $query);

            $result = mysqli_query($conn,$query);

            $total = mysqli_num_rows($result);



            if ($total != 0) { ?>

                <!-- <tr rowspan="2">
                    <th colspan='8'>
                        <center><?= getTableFieldValue("tbl_categories", "cat_name", "cat_id", $value) ?></center>
                    </th>
                </tr>
                <tr></tr> -->

                <?

                while ($row = mysqli_fetch_assoc($result)) {
                    $total_consumed =  consume_details($row['item_id'], 0, $date, $shift_start_time, $shift_end_time, $ohc);
                    if ($total_consumed == '0' && $ZeroAllowed == "N") {
                    } else {

                ?>
                        <?php if ($newCat) {
                            $newCat = false; ?>
                            <tr rowspan="2">
                                <th colspan='8'>
                                    <center><?= getTableFieldValue("tbl_categories", "cat_name", "cat_id", $value) ?></center>
                                </th>
                            </tr>
                        <?php } ?>
                        <tr>
                            <td align="left"><?= ++$count ?></td>
                            <td align="left"><?= getItemWithFormName($row['item_id']) ?></td>
                            <td align="left"><?= freshReceivedItemBalance($row['item_id'], $date, $ohc, $shift_start_time, $shift_end_time) ?></td>

                            <td align="left"><?= prevDispensaryItemBalance($row['item_id'], $ohc, $shift, $prev_shift_id) ?></td>

                            <td align="left"><?= ceil(total_qty(freshReceivedItemBalance($row['item_id'], $date, $ohc, $shift_start_time, $shift_end_time), prevDispensaryItemBalance($row['item_id'], $ohc, $shift, $prev_shift_id))) ?></td>

                            <td align="left" width="50%"><?= consume_details($row['item_id'], 1, $date, $shift_start_time, $shift_end_time, $ohc) ?></td>

                            <td align="left"><?= consume_details($row['item_id'], 0, $date, $shift_start_time, $shift_end_time, $ohc) ?></td>

                            <td align="left"><?= ceil(balance(total_qty(freshReceivedItemBalance($row['item_id'], $date, $ohc, $shift_start_time, $shift_end_time), prevDispensaryItemBalance($row['item_id'], $ohc, $shift, $prev_shift_id)), consume_details($row['item_id'], 0, $date, $shift_start_time, $shift_end_time, $ohc))) ?></td>


                        </tr>

        <?php }
                }
            }
        } ?>
    </table>
</body>

<script>
    $(document).ready(function() {
        window.print();

    });
</script>