<?php
include("../../classes/manager.class.php");

$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$batch_date = "";
$status = "";

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

// Set default values for the month and year if not provided
$monthcount = isset($_GET['month']) ? $_GET['month'] : date('F');
$year = isset($_GET['year']) ? $_GET['year'] : date('Y');
$monthCheck = date('n', strtotime($monthcount));

// Handle the success message
if (isset($_SESSION['success_msg'])) {
    $successMsg = $_SESSION['success_msg'];
    unset($_SESSION['success_msg']); // Clear the session variable after using it
} else {
    $successMsg = "";
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
</head>
<body>
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<div id="container">
    <?php include('../includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Production </h3>
            </div>
            <div>
            <?php if (!empty($successMsg)) { ?>
                 <div id='card-alert' class='card green lighten-5'>
                      <div class='card-content green-text'>
                        <p>SUCCESS : <strong>Production  </strong>Created!</p>
                      </div>
                      <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>;
            <?php } ?>
          </div>
            
            <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
                                for ($m = 1; $m <= 12; ++$m) {
                                    $monthName = date('F', mktime(0, 0, 0, $m, 1));
                                    echo '<option value="' . $monthName . '"';
                                    if ($monthName == trim($monthcount)) {
                                        echo ' selected';
                                        $monthCheck = $m;
                                    }
                                    echo '>' . $monthName . '</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
                                $currentYear = date('Y');
                                for ($i = 0; $i <= 10; $i++) {
                                    $yearcount = $currentYear - $i;
                                    echo '<option value="' . $yearcount . '"';
                                    if ($year == $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
            // Automatically load data for the current month and year on page load
            if (isset($_GET['view']) || !isset($_GET['month'])) {
                // Fetch data from created_batch and batch_setup using the filter
                $filter = " WHERE MONTH(cb.created_date) = '$monthCheck' AND YEAR(cb.created_date) = '$year'";
                $batchDetails = BatchSetup::GetBatchDetailsByBatchId($filter);

                if ($batchDetails) {
                    $countingSr = 1;
                    echo '<table class="striped demo bordered">
        <thead>
        <tr style="border: 1px solid #666;">
            <th style="text-align: left;">S.No</th>
            <th style="text-align: left;">Date</th>
            <th style="text-align: left;">Batch Name</th>
            <th style="text-align: left;">Created Qty</th>
            <th style="text-align: left;">Product Name</th>
            <th style="text-align: Right;">Produced Quantity</th>
            <th style="text-align: Right;">Remaining Quantity</th>
            <th style="text-align: Right;">Unit Cost</th>
            <th style="text-align: Right;">Wastage (KG)</th>
            <th style="text-align: Right;">Wastgge %</th>
            <th style="text-align: Right;">Production Date</th>
        </tr>
        </thead>
        <tbody>';

foreach ($batchDetails as $detail) {
    $batch_name = $detail->batch_name;
    $batch_date = date('Y-m-d', strtotime($detail->created_date));
    $product_name = $detail->product_name;
    $created_qty = $detail->created_qty;
    $batch_id = $detail->batch_id;
    $created_batch_id = $detail->created_batch_id;

    // Check if this batch ID is already in the produced_products table
    $isProduced = ProducedProducts::IsBatchProduced($created_batch_id);

    echo '<tr style="border: 1px solid #666;">
            <td style="text-align: left;">' . $countingSr . '</td>
            <td style="text-align: left;">' .date('d-m-Y', strtotime($batch_date)). '</td>
            <td style="text-align: left;">' . $batch_name . '</td>
            <td style="text-align: left;">' . $created_qty . '</td>
            <td style="text-align: left;">' . $product_name . '</td>';
    
    if ($isProduced) {
        // Fetch produced product data
        $producedProduct = ProducedProducts::GetProducedProductDataByBatchId($created_batch_id);
        echo '<td style="text-align: Right;">' . $producedProduct->total_produced_quantity . '</td>
              <td style="text-align: Right;">' . $producedProduct->remaining_quantity . '</td>
              <td style="text-align: Right;">' . $producedProduct->unit_cost_produced . '</td>
              <td style="text-align: Right;">' . $producedProduct->wastage_qty . '</td>
              <td style="text-align: Right;">' . $producedProduct->batch_perc . '</td>
              <td style="text-align: Right;">' . date('d-m-Y', strtotime($producedProduct->production_date)) . '</td>';
    } else {
        // Show the Open Production Calculation button
        echo '<td colspan="6">
                <form action="production_calculation.php" method="post">
                    <input type="hidden" name="batch_id" value="' . $batch_id . '">
                    <input type="hidden" name="created_batch_id" value="' . $created_batch_id . '">
                    <input type="hidden" name="created_qty" value="' . $created_qty . '">
                    <button type="submit" class="btn btn-primary">Add %</button>
                </form>
              </td>';
    }

    echo '</tr>';
    $countingSr++;
}

echo '</tbody></table><br>';
                } else {
                    echo "<p>No data found for the selected period.</p>";
                }
            }
            ?>
        </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');
    });
  
  $(document).ready(function () {
    function initializeFloatThead() {
        const table = $('table.demo1');
        table.floatThead({
            position: 'fixed',
            scrollingTop: 65
        });
        table.find('thead').css('background', '#ECEFF1');
    }

    function reinitializeFloatThead() {
        const table = $('table.demo1');
        table.floatThead('destroy');
        initializeFloatThead();
    }

    // Initial load
    initializeFloatThead();

    // Reinitialize after dynamic updates
    $(document).on('submit', 'form', function () {
        setTimeout(reinitializeFloatThead, 200);
    });
});

</script>
</body>
</html>
