<?php
include("../../classes/manager.class.php");
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$customer_id = "";
$product_id = "";
$grandTotalOpening = 0;

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

if ($datefrom == "") {
    $datefrom = date('d-m-Y', strtotime("-30 days"));
} else {
    $datefrom = date("d-m-Y", strtotime($datefrom));
}
if ($dateto == "") {
    $dateto = date('d-m-Y');
} else {
    $dateto = date("d-m-Y", strtotime($dateto));
}
//$datefrom = date("d-m-Y", strtotime($datefrom));
//$dateto = date("d-m-Y", strtotime($dateto));

//$qryDate = date("Y-m-d", strtotime($datefrom));
//$qryTo = date("Y-m-d", strtotime($dateto));

$dateFromFormatted = date('Y-m-d', strtotime($datefrom));
$dateToFormatted = date('Y-m-d', strtotime($dateto));

// Initialize the filter with date range condition
//$filterReport = "AND DATE_FORMAT(i.datetime, '%Y-%m-%d') >= '$qryDate' 
 //                AND DATE_FORMAT(i.datetime, '%Y-%m-%d') <= '$qryTo'";


// Apply ingredient filter if specified
if (isset($product_id) && $product_id != 'All') {
    $filterReport .= " AND i.ingredient_id = '$product_id'";
}
// At this point, the $filterReport is ready to be passed into the method
$data = ProductionSetup::GetStockRegister($dateFromFormatted, $dateToFormatted, $product_id );

$openingBalance = $data['opening_balance'];
$transactions = $data['ledger'];


//echo json_encode($transactions, JSON_PRETTY_PRINT);
//echo json_encode($openingBalance, JSON_PRETTY_PRINT);

?>
<!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>Stock Register (Finish Material)</h3>
            </div>
            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true,
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true,
                    });
                });
            </script>
            <form action="" method="get" name="search"
                  id="searchfrm">
                <table class="table" >
                    <tr>
                        <td class="col s6">Date From<br>
                            <input type="text" name="datefrom" id="datepicker"
                                   placeholder="Date From"
                                   value="<?= $datefrom ?>" class="form-control"/>
                            <input type="hidden" name="view" id="view" class="form-control"/>
                        </td>
                        <td class="col s6"> Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="form-control"/>
                        </td>
                    </tr>
                    <tr>
                        <td class="col s12">Select Product<br>
                            <?php
                            // Fetch suppliers from your SupplierSetup table
  							$filter = "ORDER BY name";
                            $products = ProductSetup::GetProductSetupList($filter);
                            ?>
                            <select class="form-control" required id="product_id"
                                    name="product_id">
                                <option>All</option>
                                <?php
                                if ($products) {
                                    foreach ($products as $product) {
                                        echo '<option ';
                                        if ($product->id == $product_id) {
                                            echo 'selected';
                                        }
                                        echo ' value="' .$product->id . '" >' . $product->name . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </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('balance_stock_report_data-<?= date('d-m-Y-h-i-a') ?>.csv')"
    class="btn waves-effect waves-light"
    style="float:left; margin-left: 15px;">
    Export CSV
</button>

                                <button
                                    id="print"
                                    class="btn waves-effect waves-light"
                                    style="float:left; margin-left: 15px;">
                                    Print
                                </button>
                            <?php } ?>
                        </td>
                    </tr>
                </table>
            </form>
            <hr>
            <?php
            if (isset($_GET['view'])) {
                ?>
                <div id="floatThead" class="section">
                   <table class="striped demo1 bordered" id="balanceStockReport">
                        <thead>
        <tr style="border: 1px solid #666;">
            <th>Date</th>
            <th>Invoice No.</th>
            <th>Batch Number</th>
            <th style='text-align: right;'>Receiving Quantity (Dr.)</th>
            <th style='text-align: right;'>Issue Quantity (Cr.)</th>
            <th style='text-align: right;'>Balance Quantity</th>
            <th style='text-align: right;'>Price Per Kg</th>
            <th style='text-align: right;'>Exclusive S.Tax Amount</th>
            <th style='text-align: right;'>Sales Tax %</th>
            <th style='text-align: right;'>Sales Tax Amount</th>
        </tr>
    </thead>
  <tbody>
<?php
$grandTotalReceivingQty = $grandTotalIssueQty = $grandTotalBalanceQty = $grandTotalAmount = $grandTotalSalesTaxAmount = $grandTotalOpening = 0;

// Get all unique product IDs and names
$products = [];

// From opening balance
foreach ($openingBalance as $opening) {
    $products[$opening->{'Product ID'}] = $opening->{'Product Name'};
}

foreach ($transactions as $row) {
    if (!isset($products[$row->{'Product ID'}])) {
        $products[$row->{'Product ID'}] = $row->{'Product Name'};
    }
}

asort($products);

// Process each product
foreach ($products as $productId => $productName) {
    $opening = array_values(array_filter($openingBalance, function ($i) use ($productId) {
        return $i->{'Product ID'} == $productId;

    }))[0] ?? [
        'Opening Balance Quantity' => 0,
        'Opening Balance Value' => 0,
        'Weighted Average Cost Per Unit' => 0,
        'Product Name' => ''
    ];

    $openingQty = $opening->{'Opening Balance Quantity'};
$openingVal = $opening->{'Opening Balance Value'};

    $taxRate = 18; // Static as per your method

    $balanceQty = $openingQty;
    $balanceAmount = $openingVal;

    $totalReceivingQty = $totalIssueQty = $totalAmount = $totalSalesTaxAmount = 0;

    echo "<tr><td colspan='10'><strong>Product: {$productName}</strong></td></tr>";

    // Opening Balance Row
    echo "
        <tr>
            <td></td>
            <td><strong>Opening Balance</strong></td>
            <td></td>
            <td style='text-align: right;'><strong>" . number_format($openingQty, 6) . "</strong></td>
            <td></td>
            <td style='text-align: right;'><strong>" . number_format($balanceQty, 6) . "</strong></td>
            <td style='text-align: right;'><strong>" . number_format($opening->{'Weighted Average Cost Per Unit'}, 2) . "</strong></td>
            <td style='text-align: right;'><strong>" . number_format($openingVal, 2) . "</strong></td>
            <td style='text-align: right;'><strong>" . number_format($taxRate, 2) . "</strong></td>
            <td style='text-align: right;'><strong>" . number_format(($openingVal * $taxRate) / 100, 2) . "</strong></td>
        </tr>";

    foreach ($transactions as $row) {
        if ($row->{'Product ID'} != $productId) continue;

        $balanceQty += $row->{'Receiving Quantity (Dr.)'} - $row->{'Issue Quantity (Cr.)'};
        $balanceAmount = $balanceQty * $row->{'Cost Per Unit'};

        $totalReceivingQty += $row->{'Receiving Quantity (Dr.)'};
        $totalIssueQty += $row->{'Issue Quantity (Cr.)'};
      //  $totalAmount = $balanceAmount;
       // $totalSalesTaxAmount = ($balanceAmount * $taxRate) / 100;

        echo "
        <tr>
    <td>" . date('d-m-Y', strtotime($row->{'Transaction Date'})) . "</td>
    <td>{$row->{'Invoice Number'}}</td>
    <td>{$row->{'Batch Number'}}</td>
    <td style='text-align: right;'>" . number_format($row->{'Receiving Quantity (Dr.)'}, 6) . "</td>
    <td style='text-align: right;'>" . number_format($row->{'Issue Quantity (Cr.)'}, 6) . "</td>
    <td style='text-align: right;'>" . number_format($balanceQty, 6) . "</td>
    <td style='text-align: right;'>" . number_format($row->{'Cost Per Unit'}, 2) . "</td>
    <td style='text-align: right;'>" . number_format($balanceAmount, 2) . "</td>
    <td style='text-align: right;'>" . number_format($taxRate, 2) . "</td>
    <td style='text-align: right;'>" . number_format($totalSalesTaxAmount, 2) . "</td>
</tr>";
    }
  // If no transactions occurred, use opening values
if ($totalReceivingQty == 0 && $totalIssueQty == 0) {
    $totalAmount = $openingVal;
    $totalSalesTaxAmount = ($openingVal * $taxRate) / 100;
} else {
    $totalAmount = $balanceAmount;
    $totalSalesTaxAmount = ($balanceAmount * $taxRate) / 100;
}

    // Totals per product
    echo "
    <tr style='font-weight: bold; background-color: #f2f2f2;'>
        <td style='text-align: right;'>Total: {$productName}</td>
        <td></td>
        <td>Op.Qty: " . number_format($openingQty, 6) . "</td>
        <td style='text-align: right;'>" . number_format($totalReceivingQty, 6) . "</td>
        <td style='text-align: right;'>" . number_format($totalIssueQty, 6) . "</td>
        <td style='text-align: right;'>" . number_format($balanceQty, 6) . "</td>
        <td></td>
        <td style='text-align: right;'>" . number_format($totalAmount, 2) . "</td>
        <td></td>
        <td style='text-align: right;'>" . number_format($totalSalesTaxAmount, 2) . "</td>
    </tr>";

    $grandTotalOpening += $openingQty;
    $grandTotalReceivingQty += $totalReceivingQty;
    $grandTotalIssueQty += $totalIssueQty;
    $grandTotalBalanceQty += $balanceQty;
    $grandTotalAmount += $totalAmount;
    $grandTotalSalesTaxAmount += $totalSalesTaxAmount;
}

// Grand Total
echo "
<tr style='font-weight: bold; background-color: #d3d3d3;'>
    <td style='text-align: right;'>Grand Total</td>
    <td></td>
    <td style='text-align: left;'>Total Op.Qty: " . number_format($grandTotalOpening, 6) . "</td>
    <td style='text-align: right;'>" . number_format($grandTotalReceivingQty, 6) . "</td>
    <td style='text-align: right;'>" . number_format($grandTotalIssueQty, 6) . "</td>
    <td style='text-align: right;'>" . number_format($grandTotalBalanceQty, 6) . "</td>
    <td></td>
    <td style='text-align: right;'>" . number_format($grandTotalAmount, 2) . "</td>
    <td></td>
    <td style='text-align: right;'>" . number_format($grandTotalSalesTaxAmount, 2) . "</td>
</tr>";
?>
</tbody>




            
            	   </table>
                </div>
                <?php
            } // close view
            ?>
        </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/stock_register_produced_products.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>
  <script type="text/javascript">
    function exportTableToCSV(filename) {
        var csv = [];
        var rows = document.querySelectorAll("table.demo1 tr");

        // Loop through each row in the table
        for (var i = 0; i < rows.length; i++) {
            var row = [], cols = rows[i].querySelectorAll("td, th");

            // Loop through each column in the row
            for (var j = 0; j < cols.length; j++) {
                // Clean and escape double quotes for CSV compatibility
                var cellValue = cols[j].innerText.trim().replace(/"/g, '""');
                row.push('"' + cellValue + '"');
            }

            // Push the row into the CSV array
            csv.push(row.join(","));
        }

        // Create CSV file and trigger download
        downloadCSV(csv.join("\n"), filename);
    }

    function downloadCSV(csv, filename) {
        var csvFile;
        var downloadLink;

        // Create a Blob from the CSV data
        csvFile = new Blob([csv], {type: "text/csv"});

        // Create a link element for download
        downloadLink = document.createElement("a");

        // Set the download filename
        downloadLink.download = filename;

        // Create a link to the CSV file
        downloadLink.href = window.URL.createObjectURL(csvFile);

        // Hide the download link
        downloadLink.style.display = "none";

        // Append the link to the body
        document.body.appendChild(downloadLink);

        // Automatically click the link to trigger the download
        downloadLink.click();

        // Remove the link from the document after download
        document.body.removeChild(downloadLink);
    }
</script>
  
</body>
</html>
