<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$supplier_id = "";
$json = 0;
$sales_tax_filter = "all";

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
extract($_REQUEST);
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("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));

$purchases = PurchaseSetup::GetSupplierPurchaseReport($dateFromFormatted, $dateToFormatted, $supplier_id, $sales_tax_filter);

?>
<?php
header('Content-Type: text/html; charset=UTF-8');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <?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>Purchase Report</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 s6">Supplier<br>
                            <?php
                            // Fetch suppliers from your SupplierSetup table
                            $suppliers = SupplierSetup::GetSupplierSetupList();
                            ?>
                            <select class="form-control" required id="supplier_id"
                                    name="supplier_id">
                                <option>All</option>
                                <?php
                                if ($suppliers) {
                                    foreach ($suppliers as $supplier) {
                                        echo '<option ';
                                        if ($supplier->id == $supplier_id) {
                                            echo 'selected';
                                        }
                                        echo ' value="' . $supplier->id . '" >' . $supplier->name . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </td>
                       <td class="col s6">Sales Tax Filter<br>
                            <select class="form-control" id="sales_tax_filter" name="sales_tax_filter">
                                <option value="all" <?= ($sales_tax_filter == "all") ? "selected" : "" ?>>Show All</option>
                                <option value="zero" <?= ($sales_tax_filter == "zero") ? "selected" : "" ?>>Show 0 Sales Tax</option>
                                <option value="nonzero" <?= ($sales_tax_filter == "nonzero") ? "selected" : "" ?>>nonzero</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('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; font-weight: bold;">
                              <th style='text-align: left;'>S.No.</th>
                              <th style='text-align: left;'>Supplier Name</th>
                              <th style='text-align: left;'>D.C. No</th>
                              <th style='text-align: left;'>D.C. Date</th>
                              <th style='text-align: left;'>Item</th>
                              <th style='text-align: right;'>Quantity</th>
                              <th style='text-align: right;'>Price</th>
                              <th style='text-align: right;'>Ex.Sales Tax Amount</th>
                              <th style='text-align: right;'>Sales Tax Amount</th>
                              <th style='text-align: right;'>Including Sales Tax Amount</th>
                          </tr>
    </thead>
<tbody>
<?php
$count = 0;
$grandTotalQty = $grandTotalExAmount = $grandTotalTax = $grandTotalIncAmount = 0;

$supplierSubtotalQty = $supplierSubtotalExAmount = $supplierSubtotalTax = $supplierSubtotalIncAmount = 0;
$currentSupplierId = null;
$supplierName = '';

foreach ($purchases as $row) {
    // Check if the supplier has changed to display subtotals for the previous supplier
    if ($currentSupplierId !== null && $currentSupplierId !== $row['supplier_id']) {
        // Display subtotal row for the previous supplier
        echo "
            <tr style='border: 1px solid; font-weight: bold; background-color: #f2f2f2;'>
            	<td></td>
                <td></td>
                <td></td>
                <td></td>
                
                <td style='text-align: right;'>Total for {$supplierName}</td>
                <td style='text-align: right;'>" . number_format($supplierSubtotalQty, 4) . "</td>
                <td></td>
                <td style='text-align: right;'>" . number_format($supplierSubtotalExAmount, 2) . "</td>
                <td style='text-align: right;'>" . number_format($supplierSubtotalTax, 2) . "</td>
                <td style='text-align: right;'>" . number_format($supplierSubtotalIncAmount, 2) . "</td>
                <td colspan='2'></td>
            </tr>
        ";

        // Reset subtotals for the next supplier
        $supplierSubtotalQty = $supplierSubtotalExAmount = $supplierSubtotalTax = $supplierSubtotalIncAmount = 0;
    }

    // Update the current supplier ID and name for the new row
    $currentSupplierId = $row['supplier_id'];
    $supplierName = $row['supplier_name'];

    // Display invoice header row
    $count += 1;
    $purchaseInvoiceDate = ($row['purchase_invoice_date'] !== '0000-00-00') ? date('d-m-Y', strtotime($row['purchase_invoice_date'])) : '-';
 	$deliveryChallanDate = ($row['delivery_challan_date'] !== '0000-00-00') ? date('d-m-Y', strtotime($row['delivery_challan_date'])) : '-';
  	$deliveryChallanNo = $row['delivery_challan_no'];
    echo "
        <tr style='border: 1px solid #666; background-color: #e8f4f8; font-weight: bold;'>
            <td style='text-align: left;'>{$count}</td>
          <td style='text-align: left;'>
    {$row['supplier_name']} - Invoice Date: {$purchaseInvoiceDate} - Invoice No: {$row['purchase_invoice_no']}
</td>

            <td></td>
            <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>    
        </tr>
    ";

    // Loop through and display each item for the current purchase
    foreach ($row['items'] as $item) {
        $itemTotal = $item['qty'] * $item['rate']; // Calculate the total amount

        echo "
            <tr style='border: 1px solid #ccc; background-color: #f9f9f9;'>
                <td></td>
                <td></td>
                <td style='text-align: left;'>{$deliveryChallanNo}</td>
                <td style='text-align: left;'> {$deliveryChallanDate} </td>
                <td style='text-align: left;'>{$item['ingredient_name']} </td>
                <td style='text-align: right;'>" . number_format($item['qty'], 4) . " " . htmlspecialchars($item['ingredient_unit']) . "</td>
                <td style='text-align: right;'>" . number_format($item['rate'], 2) . "</td>
                <td style='text-align: right;'>" . number_format($itemTotal, 2) . "</td>
                <td style='text-align: right;'>" . number_format($item['tax_amount'], 2) . "</td>
                <td style='text-align: right;'>" . number_format($itemTotal + $item['tax_amount'], 2) . "</td>
            </tr>
        ";
    }

    // Display invoice total row
    echo "
        <tr style='border: 1px solid; font-weight: bold; background-color: #f2f2f2;'>
        	<td></td>
            <td></td>
            <td></td>
            <td></td>
            <td style='text-align: right;'>Invoice Total</td>
            <td style='text-align: right;'>" . number_format($row['qty'], 4) . "</td>
            <td></td>
            <td style='text-align: right;'>" . number_format($row['total_ex_amount'], 2) . "</td>
            <td style='text-align: right;'>" . number_format($row['tax_price'], 2) . "</td>
            <td style='text-align: right;'>" . number_format($row['total_amount'], 2) . "</td>
            <td colspan='2'></td>
        </tr>
    ";

    // Accumulate supplier subtotals
    $supplierSubtotalQty += $row['qty'];
    $supplierSubtotalExAmount += $row['total_ex_amount'];
    $supplierSubtotalTax += $row['tax_price'];
    $supplierSubtotalIncAmount += $row['total_amount'];

    // Accumulate grand totals
    $grandTotalQty += $row['qty'];
    $grandTotalExAmount += $row['total_ex_amount'];
    $grandTotalTax += $row['tax_price'];
    $grandTotalIncAmount += $row['total_amount'];
}

// Display the last supplier's subtotal if there was any data processed
if ($currentSupplierId !== null) {
    echo "
        <tr style='font-weight: bold; background-color: #f2f2f2;'>
        	<td></td>
            <td></td>
            <td></td>
            <td></td>
            <td style='text-align: left;'>Total for {$supplierName}</td>
            <td style='text-align: right;'>" . number_format($supplierSubtotalQty, 4) . "</td>
            <td></td>
            <td style='text-align: right;'>" . number_format($supplierSubtotalExAmount, 2) . "</td>
            <td style='text-align: right;'>" . number_format($supplierSubtotalTax, 2) . "</td>
            <td style='text-align: right;'>" . number_format($supplierSubtotalIncAmount, 2) . "</td>
            <td colspan='2'></td>
        </tr>
    ";
}

// Display grand total row at the end
echo "
    <tr style='font-weight: bold; background-color: #d3d3d3;'>
    	<td></td>
        <td></td>
        <td></td>
        <td></td>
        <td style='text-align: right;'>Grand Total</td>
        <td style='text-align: right;'>" . number_format($grandTotalQty, 4) . "</td>
        <td></td>
        <td style='text-align: right;'>" . number_format($grandTotalExAmount, 2) . "</td>
        <td style='text-align: right;'>" . number_format($grandTotalTax, 2) . "</td>
        <td style='text-align: right;'>" . number_format($grandTotalIncAmount, 2) . "</td>
        <td colspan='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="application/javascript">
    $(document).ready(function () {
        // initialize
        $('#sub_category').material_select();
        // setup listener for custom event to re-initialize on change
        $('#sub_category').on('contentChanged', function () {
            $(this).material_select();
        });

        $('#category_name').on('change', function () {
            $('body.container').block({message: 'Loading...'});
            $.get('getFilterPurchaseCat.php?id=' + $(this).val(), function (data) {
                $("#sub_category").empty();
                $("#sub_category").append(data);
                $('body.container').unblock();
                $('#sub_category').trigger('contentChanged');
            });
        });
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/purchase-report.php?").submit();
            setTimeout(function () {
                $('#searchfrm').prop('target', "");
                $('#searchfrm').prop('action', "");
            }, fewSeconds * 1000);
        });
    });
  function exportTableToCSV(filename) {
    var csv = [];
    var rows = document.querySelectorAll("#balanceStockReport tr"); // ✅ Corrected table ID reference

    if (rows.length === 0) {
        alert("No data available for export.");
        return;
    }

    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th");

        for (var j = 0; j < cols.length; j++) {
            var cellValue = cols[j].innerText.trim().replace(/"/g, '""'); // ✅ Escape double quotes properly
            row.push('"' + cellValue + '"');
        }
        csv.push(row.join(","));
    }

    downloadCSV(csv.join("\n"), filename);
}

function downloadCSV(csv, filename) {
    var csvFile = new Blob([csv], { type: "text/csv" });
    var downloadLink = document.createElement("a");
    
    downloadLink.download = filename;
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";

    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

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