<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include("db/cn.php");
include("common/tx.php");
ob_start();
if(isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}

// Fetch filter parameters from the form
$supplier = isset($_POST['supplier']) ? $_POST['supplier'] : '';
$company = isset($_POST['company']) ? $_POST['company'] : '';
$product = isset($_POST['product']) ? $_POST['product'] : '';
$company_category = isset($_POST['company_category']) ? $_POST['company_category'] : '';
$startDate = isset($_POST['startDate']) ? $_POST['startDate'] : '';
$endDate = isset($_POST['endDate']) ? $_POST['endDate'] : '';

// Fetch supplier, company, category, and product data for form select options
$rec_suplier_name = mysqli_query($connection, "SELECT DISTINCT supplier FROM products WHERE supplier IS NOT NULL AND supplier != '' GROUP BY supplier");
$rec_suplier_company = mysqli_query($connection, "SELECT DISTINCT company FROM products WHERE company IS NOT NULL AND company != '' GROUP BY company");
$rec_suplier_company_category = mysqli_query($connection, "SELECT DISTINCT category FROM products WHERE category IS NOT NULL AND category != '' GROUP BY category");
$rec_products = mysqli_query($connection, "SELECT DISTINCT product_name FROM products WHERE product_name IS NOT NULL AND product_name != '' GROUP BY product_name");

// Base SQL query for totals
$sql_totals = "SELECT 
            SUM(quantity) AS total_quantity, 
            SUM(total_amount) AS total_amount 
        FROM 
            products 
        WHERE 1";

// Add filters based on selected options
if (!empty($supplier)) {
    $sql_totals .= " AND supplier = '" . mysqli_real_escape_string($connection, $supplier) . "'";
}

if (!empty($company)) {
    $sql_totals .= " AND company = '" . mysqli_real_escape_string($connection, $company) . "'";
}

if (!empty($company_category)) {
    $sql_totals .= " AND category = '" . mysqli_real_escape_string($connection, $company_category) . "'";
}
if (!empty($product)) {
    $sql_totals .= " AND product_name = '" . mysqli_real_escape_string($connection, $product) . "'";
}
if (!empty($startDate) && !empty($endDate)) {
    $sql_totals .= " AND DATE(date_time) >= '" . mysqli_real_escape_string($connection, $startDate) . "' AND DATE(date_time) <= '" . mysqli_real_escape_string($connection, $endDate) . "'";
}

// Execute the query
$sum_result = mysqli_query($connection, $sql_totals);
$row = mysqli_fetch_assoc($sum_result);

// Check if the keys exist before accessing them
$total_quantity = isset($row['total_quantity']) ? $row['total_quantity'] : 0;
$total_amount = isset($row['total_amount']) ? $row['total_amount'] : 0;

// Prevent division by zero if $total_quantity is zero
$final = ($total_quantity != 0) ? ($total_amount / $total_quantity) : "Undefined";

// Main query for displaying products
$sql_products = "SELECT * FROM products WHERE 1";

if (!empty($supplier)) {
    $sql_products .= " AND supplier = '" . mysqli_real_escape_string($connection, $supplier) . "'";
}

if (!empty($company)) {
    $sql_products .= " AND company = '" . mysqli_real_escape_string($connection, $company) . "'";
}

if (!empty($company_category)) {
    $sql_products .= " AND category = '" . mysqli_real_escape_string($connection, $company_category) . "'";
}
if (!empty($product)) {
    $sql_products .= " AND product_name = '" . mysqli_real_escape_string($connection, $product) . "'";
}
if (!empty($startDate) && !empty($endDate)) {
    $sql_products .= " AND DATE(date_time) >= '" . mysqli_real_escape_string($connection, $startDate) . "' AND DATE(date_time) <= '" . mysqli_real_escape_string($connection, $endDate) . "'";
}

$sql_products .= " ORDER BY date_time DESC";
$rec_purchases = mysqli_query($connection, $sql_products);

// Calculate total sum for display
$total_sum = $total_amount;

ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title><?php echo $tx; ?></title>

    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Custom styles for this template-->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.css" rel="stylesheet">
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<style>
    body {
        font-family: 'Quicksand', sans-serif;
    }
    .chart-container {
        position: relative;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 10px;
        padding: 15px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }
    canvas {
        max-width: 100%;
        height: auto;
    }
    .bg-gradient-primary {
        background: #0A4657;
        color: #fff;
    }
    .btn-primary {
        background: #0A4657;
        color: #fff;
        border: 1px #0A4657 solid;
    }  
    .btn-primary:hover {
        background: #fff;
        border: 1px #0A4657 solid;
        color: #0A4657;
    }     
    .fa-download:hover {
        color: #953E39;
    }
    .btn, .form-control, tr {
        font-weight: 700;
    }
    #table-container-wrapper {
        max-height: 460px;
        overflow-y: auto;
    }
    .report-header {
        background: #0A4657;
        color: white;
        padding: 10px;
    }
    .summary-table {
        width: 100%;
        margin-top: 20px;
        border-collapse: collapse;
    }
    .summary-table th, .summary-table td {
        padding: 12px;
        border: 1px solid #ddd;
    }
    .summary-table th {
        background: #0A4657;
        color: white;
        width: 200px;
    }
    .summary-table td {
        background: #f8f9fc;
        font-weight: 600;
    }
    .form-control, select, option{
        font-weight:700;
        color:#000;
    }
</style>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <?php include("common/sd.php"); ?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
                    <!-- Sidebar Toggle (Topbar) -->
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>
                    <?php include('common/log.php'); ?>
                </nav>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-sm-3">
                            <h3 style="font-weight:700; color:#060606;">Inventory Report</h3>
                        </div>
                        <div class="col-sm-6"></div>
                        <div class="col-sm-3"></div>
                    </div>

                    <br>
                    
                    <!-- FORM START - This was missing! -->
                    <form method="post" action="">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="supplier">Supplier Name:</label>
                                    <select class="form-control" name="supplier">
                                        <option value="">Select Supplier</option>
                                        <?php 
                                        mysqli_data_seek($rec_suplier_name, 0);
                                        while ($row_supplier_name = mysqli_fetch_array($rec_suplier_name)) { ?>
                                            <option value="<?php echo htmlspecialchars($row_supplier_name['supplier']); ?>" <?php if($supplier == $row_supplier_name['supplier']) echo 'selected'; ?>>
                                                <?php echo htmlspecialchars($row_supplier_name['supplier']); ?>
                                            </option>
                                        <?php } ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="company">Supplier Company:</label>
                                    <select class="form-control" name="company">
                                        <option value="">Select Company</option>
                                        <?php 
                                        mysqli_data_seek($rec_suplier_company, 0);
                                        while ($row_supplier_company = mysqli_fetch_array($rec_suplier_company)) { ?>
                                            <option value="<?php echo htmlspecialchars($row_supplier_company['company']); ?>" <?php if($company == $row_supplier_company['company']) echo 'selected'; ?>>
                                                <?php echo htmlspecialchars($row_supplier_company['company']); ?>
                                            </option>
                                        <?php } ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="company_category">Category:</label>
                                    <select class="form-control" name="company_category">
                                        <option value="">Select Category</option>
                                        <?php 
                                        mysqli_data_seek($rec_suplier_company_category, 0);
                                        while ($row_supplier_category = mysqli_fetch_array($rec_suplier_company_category)) { ?>
                                            <option value="<?php echo htmlspecialchars($row_supplier_category['category']); ?>" <?php if($company_category == $row_supplier_category['category']) echo 'selected'; ?>>
                                                <?php echo htmlspecialchars($row_supplier_category['category']); ?>
                                            </option>
                                        <?php } ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="product">Product Name:</label>
                                    <select class="form-control" name="product">
                                        <option value="">Select Product</option>
                                        <?php 
                                        mysqli_data_seek($rec_products, 0);
                                        while ($row_products = mysqli_fetch_array($rec_products)) { ?>
                                            <option value="<?php echo htmlspecialchars($row_products['product_name']); ?>" <?php if($product == $row_products['product_name']) echo 'selected'; ?>>
                                                <?php echo htmlspecialchars($row_products['product_name']); ?>
                                            </option>
                                        <?php } ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="startDate">Start Date:</label>
                                    <input type="date" class="form-control" name="startDate" value="<?php echo htmlspecialchars($startDate); ?>">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="endDate">End Date:</label>
                                    <input type="date" class="form-control" name="endDate" value="<?php echo htmlspecialchars($endDate); ?>">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <button type="submit" class="btn btn-primary" name="filter" style="margin-top:30px;">
                                        <i class="fas fa-filter fa-1x"></i>&nbsp;Filter
                                    </button>
                                    <a href="report_i.php" class="btn btn-dark" style="margin-top:30px;">
                                        <i class="fas fa-sync-alt fa-1x"></i>&nbsp;Reset
                                    </a>
                                    <button id="downloadExcel" type="button" class="btn btn-success" style="margin-top:30px;">
                                        <i class="fas fa-file-excel"></i>&nbsp;Excel
                                    </button>
                                    <button id="downloadPdf" type="button" class="btn btn-danger" style="margin-top:30px;">
                                        <i class="fas fa-file-pdf"></i>&nbsp;PDF
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                    <!-- FORM END -->
                    
                    <div id='report'>
                        <div class="col-sm-12" id="table-container-wrapper">
                            <table id="patientTable" class="table table-striped table-hover text-center table-sm bg-white">
                                <thead class="font-weight-bold text-center">
                                    <tr>
                                        <th colspan="10" class="report-header">Report Date Range</th>
                                    </tr>
                                    <tr>
                                        <th colspan="10"><?php echo htmlspecialchars($startDate) . ' &nbsp;To&nbsp; ' . htmlspecialchars($endDate); ?></th>
                                    </tr>
                                </thead>
                                <thead style="background:#0A4657; color:white;">
                                    <tr>
                                        <th colspan="10" class="text-center p-3">Inventory Report Information</th>
                                    </tr>
                                </thead>
                                <thead>
                                    <tr class="bg-dark text-white">
                                        <th>Date</th>
                                        <th>Supplier</th>
                                        <th>Company</th>
                                        <th>Category</th>
                                        <th>Product Name</th>
                                        <th>T.P</th>
                                        <th>Total Quantity</th>
                                        <th>Total Amount (Rs)</th>
                                        <th>Type</th>
                                        <th>Batch</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $row_count = 0;
                                    if ($rec_purchases) {
                                        while ($row = mysqli_fetch_array($rec_purchases)) { 
                                            $row_count++;
                                            ?>
                                            <tr style="color:#060606;">
                                                <td><?php echo htmlspecialchars($row['date_time']); ?></td>
                                                <td class="text-capitalize"><?php echo htmlspecialchars($row['supplier']); ?></td>
                                                <td class="text-capitalize"><?php echo htmlspecialchars($row['company']); ?></td>
                                                <td class="text-capitalize"><?php echo htmlspecialchars($row['category']); ?></td>
                                                <td class="text-capitalize"><?php echo htmlspecialchars($row['product_name']); ?></td>
                                                <td><?php echo number_format($row['trade_price'], 2); ?></td> 
                                                <td><?php echo number_format($row['quantity'], 0); ?></td>
                                                <td><?php echo number_format($row['total_amount'], 2); ?></td>
                                                <td class="text-capitalize"><?php echo htmlspecialchars($row['p_type']); ?></td>
                                                <td class="text-capitalize"><?php echo htmlspecialchars($row['batch_no']); ?></td>
                                            </tr>
                                        <?php } 
                                    } ?>
                                    <?php if ($row_count == 0): ?>
                                        <tr>
                                            <td colspan="10" class="text-center text-muted">No records found for the selected criteria.</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- Summary Table -->
                        <table class="table bg-white mt-3 summary-table">
                            <tfoot>
                                <tr>
                                    <th>Total Quantity:</th>
                                    <td><?php echo number_format($total_quantity, 0); ?></td>
                                </tr>
                                <tr>
                                    <th>Total Amount:</th>
                                    <td>Rs <?php echo number_format($total_sum, 2); ?> /-</td>
                                </tr>
                                <tr>
                                    <th>Total Records:</th>
                                    <td><?php echo number_format($row_count, 0); ?></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
                <!-- /.container-fluid -->
            </div>
            <br><br>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php"); ?>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="logout.php">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    
    <script>
    /* ================= EXCEL ================= */
    document.getElementById('downloadExcel').addEventListener('click', function (e) {
        e.preventDefault();

        var mainTable = document.getElementById('patientTable');
        var summaryTable = document.querySelector('.summary-table');
        
        if (!mainTable) {
            alert("Table not found");
            return;
        }

        var mainClone = mainTable.cloneNode(true);
        var summaryClone = summaryTable.cloneNode(true);
        
        var wrapper = document.createElement('div');
        wrapper.appendChild(mainClone);
        
        var spacer = document.createElement('div');
        spacer.style.height = '20px';
        wrapper.appendChild(spacer);
        
        wrapper.appendChild(summaryClone);

        var wb = XLSX.utils.table_to_book(wrapper, { sheet: "Inventory", raw: true });
        var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
        
        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
        
        saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), 'Inventory_Report.xlsx');
    });

    /* ================= PDF ================= */
    document.getElementById("downloadPdf").addEventListener("click", function (e) {
        e.preventDefault();

        const { jsPDF } = window.jspdf;
        const report = document.getElementById("report");

        if (!report) {
            alert("Report container not found");
            return;
        }

        const now = new Date();
        const formattedDateTime = now.toLocaleDateString() + " " + now.toLocaleTimeString();

        html2canvas(report, { scale: 2, logging: false, allowTaint: true, useCORS: true }).then(canvas => {
            const imgData = canvas.toDataURL("image/jpeg", 0.8);
            const pdf = new jsPDF("p", "mm", "a4");
            const pdfWidth = pdf.internal.pageSize.getWidth();
            const pdfHeight = pdf.internal.pageSize.getHeight();
            const imgHeight = (canvas.height * pdfWidth) / canvas.width;
            
            let heightLeft = imgHeight;
            let position = 0;

            pdf.setFont("helvetica", "bold");
            pdf.setFontSize(16);
            pdf.text("Whole Sale Retail", 14, 15);
            pdf.setFont("helvetica", "normal");
            pdf.setFontSize(10);
            pdf.text("Address: Al-Hafeez Shopping Mall, Gulberg III Lahore.", 14, 20);
            pdf.text("Phone: 0334-8739892, Whatsapp: 0334-8739892", 14, 25);
            pdf.text("Email: info@atrsms.pk", 14, 30);
            
            pdf.setFont("helvetica", "bold");
            pdf.setFontSize(14);
            pdf.text("Inventory Report", pdfWidth - 14, 15, { align: "right" });
            pdf.setFontSize(10);
            pdf.text(`Printed: ${formattedDateTime}`, pdfWidth - 14, 20, { align: "right" });

            pdf.addImage(imgData, "JPEG", 0, 35, pdfWidth, imgHeight);
            
            if (heightLeft > pdfHeight) {
                heightLeft -= pdfHeight;
                while (heightLeft > 0) {
                    position = heightLeft - imgHeight;
                    pdf.addPage();
                    pdf.addImage(imgData, "JPEG", 0, position, pdfWidth, imgHeight);
                    heightLeft -= pdfHeight;
                }
            }

            pdf.save("Inventory-Report.pdf");

        }).catch(err => {
            console.error(err);
            alert("PDF generation failed");
        });
    });
    </script>
    
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>
</body>
</html>