<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$batch_date = "";
$totalqty = 0;
$totalOil = 0;
$totalMung = 0;
$totalMash = 0;
$totalRice = 0;
$totalpackets = 0;
$totalpropackets =0;
$Grandtotalqty = 0;
$GrandtotalOil = 0;
$GrandtotalMung = 0;
$GrandtotalMash = 0;
$GrandtotalRice = 0;
$Grandtotalpackets = 0;
$Grandtotalpropackets = 0;
$status = "";
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
extract($_REQUEST);
$actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if ($datefrom == "") {
    $datefrom = date('Y-m-d', strtotime("-30 days"));
} else {
    $datefrom = date("Y-m-d", strtotime($datefrom));
}
if ($dateto == "") {
    $dateto = date('Y-m-d');
} else {
    $dateto = date("Y-m-d", strtotime($dateto));
}
$datefrom = date("Y-m-d", strtotime($datefrom));
$dateto = date("Y-m-d", strtotime($dateto));

$qryDate = date("Y-m-d", strtotime($datefrom));
$qryTo = date("Y-m-d", strtotime($dateto));
if (isset($_POST) && !empty($_POST['production']) && $_POST['production'] == 1) {
    $productionSet = ProductionSetup::GetProductionSetupById($production_id);
    $oil = 0;
    $mash = 0;
    $mung = 0;
    $rice = 0;
    $oilavailability = 0;
    $mungavailability = 0;
    $mashavailability = 0;
    $riceavailability = 0;
    if (!empty($productionSet)) {
        if(!empty($productionSet->per_unit_oil) && $productionSet->per_unit_oil != 0){
            $oil = $productionSet->batch_qty*$productionSet->per_unit_oil;
        }
        if(!empty($productionSet->per_unit_mung) && $productionSet->per_unit_mung != 0){
            $mung = $productionSet->batch_qty*$productionSet->per_unit_mung;
        }
        if(!empty($productionSet->per_unit_mash) && $productionSet->per_unit_mash != 0){
            $mash = $productionSet->batch_qty*$productionSet->per_unit_mash;
        }
        if(!empty($productionSet->per_unit_rice) && $productionSet->per_unit_rice != 0){
            $rice = $productionSet->batch_qty*$productionSet->per_unit_rice;
        }
        $ing = IngSetup::GetIngSetupList();
        foreach($ing AS $ingRow){
            if($ingRow->id == 1){
                $oilavailability = $ingRow->availability;
            }
            if($ingRow->id == 2){
                $mungavailability = $ingRow->availability;
            }
            if($ingRow->id == 3){
                $mashavailability = $ingRow->availability;
            }
            if($ingRow->id == 4){
                $riceavailability = $ingRow->availability;
            }
        }
    }
    if($status != 'cancel' && $oilavailability >= $oil && $mungavailability >= $mung && $mashavailability >= $mash && $riceavailability >= $rice){

        $oilavailability -= $oil;
        $dataProduct['availability'] = $oilavailability;
        IngSetup::UpdateIngSetup(1, $dataProduct);

        $mungavailability -= $mung;
        $dataProduct['availability'] = $mungavailability;
        IngSetup::UpdateIngSetup(2, $dataProduct);

        $mashavailability -= $mash;
        $dataProduct['availability'] = $mashavailability;
        IngSetup::UpdateIngSetup(3, $dataProduct);

        $riceavailability -= $rice;
        $dataProduct['availability'] = $riceavailability;
        IngSetup::UpdateIngSetup(4, $dataProduct);

        extract($_REQUEST);
        $data['total'] = $produced_qty;
        $data['status'] = $status;
        $q = ProductionSetup::UpdateProductionSetup($production_id, $data);

        $batch = BatchSetup::GetBatchSetupById($productionSet->batch_id);
        $product = ProductSetup::GetProductSetupById($batch->product_id);
        if (!empty($product)) {

            //Add Stock
            $dataStock['product_id'] = $batch->product_id;
            $dataStock['qty'] = $produced_qty;
            $dataStock['user_id'] = $_SESSION['sess_userid'];
            $dataStock['datetime'] = 'NOW()';
            Stock::AddStockSetup($dataStock);

            //Update Availability in product stock
            $availableStock = $product->availability;
            $totalStock = $availableStock + $produced_qty;
            $dataProduct['availability'] = $totalStock;
            ProductSetup::UpdateProductSetup($batch->product_id, $dataProduct);
        }
    }
    else{
        $data['status'] = $status;
        $q = ProductionSetup::UpdateProductionSetup($production_id, $data);
    }
    if ($q) {
        ?>
        <script>window.location.href = '<?=$actual_link?>'</script>
        <?php
    } else {
        echo "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>Some error occurred!</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
</head>
<body>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('../includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Production Report</h3>
            </div>
            <?php if (isset($_GET['sucess'])) { ?>
                <div class="alert alert-success  fade in">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    <strong>*</strong> Successfully Updated.
                </div>
            <?php } ?>
            <?php if (isset($_GET['error'])) { ?>
                <div class="alert alert-error  fade in">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    Error Ocurred. Try Again Later.
                </div>
            <?php } ?>
            <?php if (isset($_GET['availed'])) { ?>
                <div class="alert alert-error  fade in">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    Your leaves limit is over. Contact to admin
                </div>
            <?php } ?>
            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                    });
                });
            </script>
            <form action="" method="get" name="search"
                  id="searchfrm">
                <table class="table">
                    <tr style="border-top: 1px solid #ddd;">
                        <td class="col s6">Month<br>
                            <select class="form-control" name="month" id="month">
                                <?php
                                if ($month) {
                                    $monthcount = $month;
                                } else {
                                    $monthcount = date('F');
                                }
                                for ($m = 1; $m <= 12; ++$m) {
                                    echo '<option value="' . date('F', mktime(0, 0, 0, $m, 1)) . '"';
                                    if (date('F', mktime(0, 0, 0, $m, 1)) == trim($monthcount)) {
                                        echo ' selected';
                                        $monthCheck = $m;
                                    }
                                    echo '>' . date('F', mktime(0, 0, 0, $m, 1)) . '</option>';
                                }
                                ?>
                            </select>
                            <input type="hidden" name="view" id="view" class="form-control"/>
                        </td>
                        <td class="col s6">Year<br>
                            <select class="form-control" name="year" id="year">
                                <?php
                                if ($year) {
                                    $currentYear = $year;
                                } else {
                                    $currentYear = date('Y');
                                }
                                for ($i = 1; $i <= 10; $i++) {
                                    $yearcount = 2016 + $i;
                                    echo '<option value="' . $yearcount . '"';
                                    if ($currentYear == $yearcount) {
                                        echo ' selected';
                                    }
                                    echo '>' . $yearcount . '</option>';
                                }
                                ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" class="col s12">
                            <button type="submit" class="btn waves-effect waves-light"
                                    style="float:left;">
                                Search
                            </button>
                            <?php if (isset($_GET['view'])) { ?>
                                <button
                                    onclick="exportTableToCSV('production-<?= date('d-m-Y-h-i-a') ?>.csv')"
                                    class="btn waves-effect waves-light"
                                    style="float:left; margin-left: 15px;">
                                    Export CSV
                                </button>
                            <?php } ?>
                            <button
                                id="print"
                                class="btn waves-effect waves-light"
                                style="float:left; margin-left: 15px;">
                                Print
                            </button>
                        </td>
                    </tr>
                </table>
            </form>
            <hr><?php
            if (isset($_GET['view']) && empty($employee_id)) {
                $getYearMonth = date('Y-m-00', strtotime($year . '-' . $monthCheck . '-01'));
                $filterProductionReport = " WHERE DATE_FORMAT(batch_date,'%Y-%m-00')='$getYearMonth' AND status<>'cancel'";
                $filterProductionReport .= " ORDER BY batch_date";
                $qry = ProductionSetup::GetProductionSetupList($filterProductionReport);
                if ($qry) {
                    $countingSr = 1;
                    $counttotal = count($qry);
                    foreach ($qry AS $qryRow) {
                        if ($countingSr == 1 || $batch_date != $qryRow->batch_date) {
                            $countingSrn = 1;
                            ?>
                            <table class="striped demo1 bordered">
                            <thead>
                            <tr style="border: 1px solid #666;">
                                <th>S.No</th>
                                <th>Date</th>
                                <th>Batch Name</th>
                                <th>No. Of Bacthes</th>
                                <th>Oil</th>
                                <th>Mung Daal</th>
                                <th>Mash Daal</th>
                                <th>Rice Powder</th>
                                <th>Total Estimated</th>
                                <th>Total Produced</th>
                                <th>Difference</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
                        }
                        $totalqty += $qryRow->batch_qty;
                        $totalOil += ($qryRow->batch_qty * $qryRow->per_unit_oil);
                        $totalMung += ($qryRow->batch_qty * $qryRow->per_unit_mung);
                        $totalMash += ($qryRow->batch_qty * $qryRow->per_unit_mash);
                        $totalRice += ($qryRow->batch_qty * $qryRow->per_unit_rice);
                        $totalpackets += ($qryRow->batch_qty * $qryRow->per_unit_packets);
                        $totalpropackets += $qryRow->total;
                        echo '<tr style="border: 1px solid #666;">';
                        echo '<td style="width: 50px;">' . $countingSrn . '</td>';
                        echo '<td>' . date('Y-m-d', strtotime($qryRow->batch_date)) . '</td>';
                        echo '<td>' . $qryRow->batch_name . '</td>';
                        echo '<td>' . $qryRow->batch_qty . '</td>';
                        echo '<td>' . ($qryRow->batch_qty * $qryRow->per_unit_oil) . '</td>';
                        echo '<td>' . ($qryRow->batch_qty * $qryRow->per_unit_mung) . '</td>';
                        echo '<td>' . ($qryRow->batch_qty * $qryRow->per_unit_mash) . '</td>';
                        echo '<td>' . ($qryRow->batch_qty * $qryRow->per_unit_rice) . '</td>';
                        echo '<td>' . ($qryRow->batch_qty * $qryRow->per_unit_packets) . '</td>';
                        if ($qryRow->total == 0) {
                            ?>
                            <td>
                                <a style="color: #fff; padding: 5px; border-radius: 5px; font-size: 12px;"
                                   class="waves-effect waves-light btn-sm modal-trigger light-blue"
                                   href="#modal<?php echo $qryRow->id; ?>">Add</a>
                                <script>
                                    $(function () {
                                        $('#datepicker<?php echo $qryRow->id; ?>').pickadate({
                                            format: 'dd-mm-yyyy',
                                            selectMonths: true,
                                        });
                                    });
                                </script>
                                <form action="" method="post" id="create_production">
                                    <div id="modal<?php echo $qryRow->id; ?>" class="modal">
                                        <div class="modal-content">
                                            <p>

                                            <h3><?= $qryRow->batch_name . " - " . date('Y-m-d', strtotime($qryRow->batch_date)) ?></h3>

                                            <div class="row margin">
                                                <div class="input-field col s12">
                                                    <input type="text" name="produced_qty" required="required"
                                                           id="produced_qty" class="form-control"/>
                                                    <label for="produced_qty" class="center-align">Produced Quantity
                                                        *</label>
                                                </div>
                                            </div>
                                            <div class="row margin">
                                                <div class="input-field col s12">
                                                    <select class="form-control" name="status">
                                                        <option value="active" <?php if ($status == 'active') {
                                                            echo "selected='selected'";
                                                        } ?>>Active
                                                        </option>
                                                        <option value="cancel" <?php if ($status == 'cancel') {
                                                            echo "selected='selected'";
                                                        } ?>>Cancel
                                                        </option>
                                                    </select>
                                                    <label for="status" class="center-align">Status</label>
                                                </div>
                                            </div>
                                            <input type="hidden" name="production_id" id="production_id"
                                                   value='<?php echo $qryRow->id; ?>'>
                                            <input type="hidden" name="production" value='1'>
                                            </p>
                                        </div>
                                        <div class="modal-footer">
                                            <button id="btnsubmit" type="submit"
                                                    class="waves-effect waves-red btn-flat">
                                                Submit
                                            </button>
                                            <a href="#"
                                               class="waves-effect waves-green btn-flat modal-action modal-close">Close</a>
                                        </div>
                                    </div>
                                </form>
                            </td>
                            <?php
                            //echo '<td>' . ($qryRow->batch_qty * $qryRow->per_unit_packets) . '</td>';
                            echo '<td>-</td>';
                        } else {
                            echo '<td>' . $qryRow->total . '</td>';
                            echo '<td>' . ($qryRow->total - ($qryRow->batch_qty * $qryRow->per_unit_packets)) . '</td>';
                        }
                        echo '</tr>';
                        if ($counttotal == $countingSr || $qry[($countingSr)]->batch_date != $qryRow->batch_date) {
                            echo '<tr style="border: 1px solid #666;">';
                            echo '<td colspan="3">Total</td>';
                            echo '<td>' . $totalqty . '</td>';
                            echo '<td>' . $totalOil . '</td>';
                            echo '<td>' . $totalMung . '</td>';
                            echo '<td>' . $totalMash . '</td>';
                            echo '<td>' . $totalRice . '</td>';
                            echo '<td>' . $totalpackets . '</td>';
                            echo '<td>' . $totalpropackets . '</td>';
                            echo '<td>-</td>';
                            echo '</tr>';
                            $Grandtotalqty += $totalqty;
                            $GrandtotalOil += $totalOil;
                            $GrandtotalMung += $totalMung;
                            $GrandtotalMash += $totalMash;
                            $GrandtotalRice += $totalRice;
                            $Grandtotalpackets += $totalpackets;
                            $Grandtotalpropackets += $totalpropackets;

                            $totalqty = 0;
                            $totalOil = 0;
                            $totalMung = 0;
                            $totalMash = 0;
                            $totalRice = 0;
                            $totalpackets = 0;
                            $totalpropackets = 0;
                            ?>
                            </tbody>
                            </table>
                            <br>
                            <?php
                        }
                        $batch_date = $qryRow->batch_date;
                        $countingSr++;
                        $countingSrn++;
                    }
                    ?>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>Total No. Of Bacthes</th>
                            <th style="width: 150px;"><?= $Grandtotalqty ?></th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>Total Oil</th>
                            <th style="width: 150px;"><?= $GrandtotalOil ?></th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>Total Mung Daal</th>
                            <th style="width: 150px;"><?= $GrandtotalMung ?></th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>Total Mash Daal</th>
                            <th style="width: 150px;"><?= $GrandtotalMash ?></th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>Total Rice Powder</th>
                            <th style="width: 150px;"><?= $GrandtotalRice ?></th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>Total Estimated</th>
                            <th style="width: 150px;"><?= $Grandtotalpackets ?></th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>Total Produced</th>
                            <th style="width: 150px;"><?= $Grandtotalpropackets ?></th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>Total Difference</th>
                            <th style="width: 150px;"><?= ($Grandtotalpropackets - $Grandtotalpackets)?></th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                    <br>
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th style="text-align: center;">Stock</th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                    <?php
                    $ing = IngSetup::GetIngSetupList();
                    foreach($ing AS $ingRow){
                        if($ingRow->id == 1){
                            echo '<table class="striped bordered">
                                <thead>
                                <tr style="border: 1px solid #666;">
                                    <th>Oil</th>
                                    <th style="width: 150px;">'.$ingRow->availability.'</th>
                                </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>';
                        }
                        if($ingRow->id == 2){
                            echo '<table class="striped bordered">
                                <thead>
                                <tr style="border: 1px solid #666;">
                                    <th>Mung</th>
                                    <th style="width: 150px;">'.$ingRow->availability.'</th>
                                </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>';
                        }
                        if($ingRow->id == 3){
                            echo '<table class="striped bordered">
                                <thead>
                                <tr style="border: 1px solid #666;">
                                    <th>Mash</th>
                                    <th style="width: 150px;">'.$ingRow->availability.'</th>
                                </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>';
                        }
                        if($ingRow->id == 4){
                            echo '<table class="striped bordered">
                                <thead>
                                <tr style="border: 1px solid #666;">
                                    <th>Rice</th>
                                    <th style="width: 150px;">'.$ingRow->availability.'</th>
                                </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>';
                        }
                    }
                }

                $filterProductionTotalReport = " WHERE DATE_FORMAT(batch_date,'%Y-%m-00')='$getYearMonth' AND status<>'cancel'";
                $filterProductionTotalReport .= " GROUP BY batch_id";
                $qryTotal = ProductionSetup::GetProductionBatchWiseTotalList($filterProductionTotalReport);
                if($qryTotal){
                    echo "<br><br>";
                    echo '<table class="striped demo1 bordered">
                                <thead>
                                <tr style="border: 1px solid #666;">
                                    <th>S.No</th>
                                    <th>Batch Name</th>
                                    <th>Batches</th>
                                    <th>Oil</th>
                                    <th>Mung</th>
                                    <th>Mash</th>
                                    <th>Rice</th>
                                    <th>Total Est.</th>
                                    <th>Total Pro.</th>
                                    <th>Total Diff.</th>
                                </tr>
                                </thead>';
                    $countPro = 1;
                    $grandbatches = 0;
                    $grandoil = 0;
                    $grandmung = 0;
                    $grandmash = 0;
                    $grandrice = 0;
                    $grandpackets = 0;
                    $grandtotal = 0;
                    $granddiff = 0;
                    foreach($qryTotal AS $qryTotalRow){
                        echo '<tbody>
                                <tr style="border: 1px solid #666;">
                                    <td>'.$countPro.'</td>
                                    <td>'.$qryTotalRow->batch_name.'</th>
                                    <td>'.$qryTotalRow->batches.'</th>
                                    <td>'.$qryTotalRow->oil.'</th>
                                    <td>'.$qryTotalRow->mung.'</th>
                                    <td>'.$qryTotalRow->mash.'</th>
                                    <td>'.$qryTotalRow->rice.'</th>
                                    <td>'.$qryTotalRow->packets.'</th>
                                    <td>'.$qryTotalRow->total.'</th>
                                    <td>'.($qryTotalRow->total - $qryTotalRow->packets).'</th>
                                </tr>
                                </tbody>';
                        $countPro++;
                        $grandbatches += $qryTotalRow->batches;
                        $grandoil += $qryTotalRow->oil;
                        $grandmung += $qryTotalRow->mung;
                        $grandmash += $qryTotalRow->mash;
                        $grandrice += $qryTotalRow->rice;
                        $grandpackets += $qryTotalRow->packets;
                        $grandtotal += $qryTotalRow->total;
                        $granddiff += ($qryTotalRow->total - $qryTotalRow->packets);
                    }
                    echo '<tbody>
                                <tr style="border: 1px solid #666;">
                                    <td></td>
                                    <td style="font-weight: bolder;">Total</th>
                                    <td>'.$grandbatches.'</th>
                                    <td>'.$grandoil.'</th>
                                    <td>'.$grandmung.'</th>
                                    <td>'.$grandmash.'</th>
                                    <td>'.$grandrice.'</th>
                                    <td>'.$grandpackets.'</th>
                                    <td>'.$grandtotal.'</th>
                                    <td>'.$granddiff.'</th>
                                </tr>
                                </tbody>';
                    echo '</table>';
                }


            } ?>
        </div>
    </div>
</div>
<?php include('../includes/inc_footer.php'); ?>
<script type="text/javascript" src="<?= PROJECT_URL ?>js/download.js"></script>
<?php include('../includes/inc_js.php'); ?>
<script type="text/javascript" src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead.min.js"></script>
<script type="text/javascript"
        src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead-slim.min.js"></script>
<script type="application/javascript">
    $(document).ready(function () {
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/production.php?").submit();
            setTimeout(function () {
                $('#searchfrm').prop('target', "");
                $('#searchfrm').prop('action', "");
            }, fewSeconds * 1000);
        });
        $('table.demo1').floatThead({
            position: 'fixed',
            scrollingTop: 65
        });
        $('table.demo1 thead').css('background', '#ECEFF1');
    });
</script>
</body>
</html>