<?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>Summary 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="balanceStockSummaryReport">
    <thead>
        <tr style='border: 1px solid #666; font-weight: bold;'>
            <th>Product Name</th>
            <th style='text-align: right;'>Opening Amount (Excl. S.Tax)</th>
            <th style='text-align: right;'>Opening S.Tax</th>
            <th style='text-align: right;'>Opening Qty</th>
            <th style='text-align: right;'>Receive Qty</th>
            <th style='text-align: right;'>Issue Qty</th>
            <th style='text-align: right;'>Balance Qty</th>
            <th style='text-align: right;'>Closing Amount (Excl. S.Tax)</th>
            <th style='text-align: right;'>Closing S.Tax</th>
        </tr>
    </thead>
 <tbody>
<?php
$taxRate = 18;

// Step 1: Collect all products from opening and transactions
$products = [];

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

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

// Sort by product name
asort($products);

// Step 2: Loop through products and calculate totals only
$grandOpeningAmount = $grandOpeningTax = $grandOpeningQty = 0;
$grandReceiveQty = $grandIssueQty = $grandBalanceQty = 0;
$grandClosingAmount = $grandClosingTax = 0;

$productSummaries = [];

foreach ($products as $productId => $productName) {
    $ob = array_values(array_filter($openingBalance, function ($item) use ($productId) {
        return $item->{'Product ID'} == $productId;
    }))[0] ?? null;

    $openingQty = $ob ? $ob->{'Opening Balance Quantity'} : 0;
    $openingAmount = $ob ? $ob->{'Opening Balance Value'} : 0;
    $openingTax = ($openingAmount * $taxRate) / 100;

    $productTransactions = array_filter($transactions, function ($item) use ($productId) {
        return $item->{'Product ID'} == $productId;
    });

    $receiveQty = $issueQty = 0;
    $closingQty = $openingQty;
    $closingAmount = $openingAmount;

    foreach ($productTransactions as $row) {
        $dr = $row->{'Receiving Quantity (Dr.)'};
        $cr = $row->{'Issue Quantity (Cr.)'};
        $cost = $row->{'Cost Per Unit'};

        $receiveQty += $dr;
        $issueQty += $cr;
        $closingQty += ($dr - $cr);
        $closingAmount = $closingQty * $cost;
    }

    $closingTax = ($closingAmount * $taxRate) / 100;

    $productSummaries[] = [
        'name' => $productName,
        'openingAmount' => $openingAmount,
        'openingTax' => $openingTax,
        'openingQty' => $openingQty,
        'receiveQty' => $receiveQty,
        'issueQty' => $issueQty,
        'closingQty' => $closingQty,
        'closingAmount' => $closingAmount,
        'closingTax' => $closingTax
    ];

    // Accumulate grand totals
    $grandOpeningAmount += $openingAmount;
    $grandOpeningTax += $openingTax;
    $grandOpeningQty += $openingQty;
    $grandReceiveQty += $receiveQty;
    $grandIssueQty += $issueQty;
    $grandBalanceQty += $closingQty;
    $grandClosingAmount += $closingAmount;
    $grandClosingTax += $closingTax;
}

// ✅ Now loop once to render rows
foreach ($productSummaries as $row) {
    echo "<tr style='border: 1px solid #666; font-weight: bold;'>
        <td>{$row['name']}</td>
        <td style='text-align: right;'>" . number_format($row['openingAmount'], 2) . "</td>
        <td style='text-align: right;'>" . number_format($row['openingTax'], 2) . "</td>
        <td style='text-align: right;'>" . number_format($row['openingQty'], 6) . "</td>
        <td style='text-align: right;'>" . number_format($row['receiveQty'], 6) . "</td>
        <td style='text-align: right;'>" . number_format($row['issueQty'], 6) . "</td>
        <td style='text-align: right;'>" . number_format($row['closingQty'], 6) . "</td>
        <td style='text-align: right;'>" . number_format($row['closingAmount'], 2) . "</td>
        <td style='text-align: right;'>" . number_format($row['closingTax'], 2) . "</td>
    </tr>";
}


// 🔥 Grand Total Row
echo "
<tr style='border: 2px solid #666; font-weight: bold;'>
    <td>Grand Total</td>
    <td style='text-align: right;'>" . number_format($grandOpeningAmount, 2) . "</td>
    <td style='text-align: right;'>" . number_format($grandOpeningTax, 2) . "</td>
    <td style='text-align: right;'>" . number_format($grandOpeningQty, 6) . "</td>
    <td style='text-align: right;'>" . number_format($grandReceiveQty, 6) . "</td>
    <td style='text-align: right;'>" . number_format($grandIssueQty, 6) . "</td>
    <td style='text-align: right;'>" . number_format($grandBalanceQty, 6) . "</td>
    <td style='text-align: right;'>" . number_format($grandClosingAmount, 2) . "</td>
    <td style='text-align: right;'>" . number_format($grandClosingTax, 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_summary.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>
