<?php
include("db/cn.php");
include("common/tx.php");
ini_set('display_errors', 1);
error_reporting(E_ALL);

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

/* ================= SESSION ================= */
if (
    !isset($_SESSION['user_name']) ||
    !isset($_SESSION['user_role']) ||
    !isset($_SESSION['outlet_name']) ||
    !isset($_SESSION['outlet_address'])
) {
    die("Session expired");
}

$userName       = $_SESSION['user_name'];
$userRole       = $_SESSION['user_role'];
$outlet_name    = $_SESSION['outlet_name'];
$outlet_address = $_SESSION['outlet_address'];

/* ================= DEFAULTS ================= */
$supplier = '';
$startDate = '';
$endDate = '';
$transactions = [];
$openingBalance = 0;
$balance = 0;

/* ================= FILTER ================= */
if (isset($_POST['filter'])) {
    $supplier  = mysqli_real_escape_string($connection, $_POST['supplier']);
    $startDate = date('Y-m-d', strtotime($_POST['startDate']));
    $endDate   = date('Y-m-d', strtotime($_POST['endDate']));

    /* ===== BASE OPENING ===== */
    $baseOpening = 0;
    $res = mysqli_query($connection,
        "SELECT open_amount FROM supplier_opening_amount
         WHERE supplier_name='$supplier' LIMIT 1"
    );
    if ($res && mysqli_num_rows($res)) {
        $baseOpening = (float)mysqli_fetch_assoc($res)['open_amount'];
    }

    /* ===== TRANSACTIONS BEFORE START DATE ===== */
    // CREDIT PURCHASES BEFORE START DATE
    $creditPurchasesBefore = mysqli_fetch_assoc(mysqli_query($connection,
        "SELECT COALESCE(SUM(discount_amount),0) total 
         FROM (
             SELECT inv_id, MAX(discount_amount) as discount_amount
             FROM purchase
             WHERE customer_name='$supplier'
             AND paid_by='Credit'
             AND status=''
             AND r_inv_id=''
             AND date_time < '$startDate'
             GROUP BY inv_id
         ) t"
    ))['total'];

    // PURCHASE RETURNS BEFORE START DATE
    $purchaseReturnsBefore = mysqli_fetch_assoc(mysqli_query($connection,
        "SELECT COALESCE(SUM(discount_amount),0) total 
         FROM (
             SELECT r_inv_id, MAX(discount_amount) as discount_amount
             FROM purchase
             WHERE customer_name='$supplier'
             AND status='return'
             AND date_time < '$startDate'
             GROUP BY r_inv_id
         ) t"
    ))['total'];

    // PAYMENTS TO SUPPLIER BEFORE START DATE
    $paymentsBefore = mysqli_fetch_assoc(mysqli_query($connection,
        "SELECT COALESCE(SUM(supplier_amount),0) total
         FROM supplier_paid
         WHERE supplier_name='$supplier'
         AND date_time < '$startDate'"
    ))['total'];

    /* ===== FINAL OPENING BALANCE ===== */
    $openingBalance =
        $baseOpening
        + $creditPurchasesBefore
        - $purchaseReturnsBefore
        - $paymentsBefore;

    $balance = $openingBalance;

    /* ================= TRANSACTIONS BETWEEN DATES ================= */

    // CREDIT PURCHASES
    $rs = mysqli_query($connection,
        "SELECT date_time date, discount_amount amount, paid_by, inv_id,
         SUM(product_quantity) total_qty
         FROM purchase
         WHERE customer_name='$supplier'
         AND paid_by='Credit'
         AND status=''
         AND r_inv_id=''
         AND date_time BETWEEN '$startDate' AND '$endDate'
         GROUP BY inv_id"
    );
    while ($r = mysqli_fetch_assoc($rs)) {
        $transactions[] = [
            'date' => $r['date'],
            'description' => 'Credit Purchase',
            'amount' => $r['amount'],
            'paid_by' => $r['paid_by'],
            'total_qty' => $r['total_qty'],
            'invoice' => $r['inv_id']
        ];
    }

    // PAYMENTS TO SUPPLIER
    $rs = mysqli_query($connection,
        "SELECT date_time date, supplier_amount as amount, status as paid_by, description
         FROM supplier_paid
         WHERE supplier_name='$supplier'
         AND date_time BETWEEN '$startDate' AND '$endDate'"
    );
    while ($r = mysqli_fetch_assoc($rs)) {
        $transactions[] = [
            'date' => $r['date'],
            'description' => 'Payment to Supplier',
            'amount' => -abs($r['amount']),
            'paid_by' => $r['paid_by'] ? ucfirst($r['paid_by']) : 'Cash',
            'total_qty' => 0,
            'invoice' => '-',
            'desc_name' => $r['description']
        ];
    }

    // PURCHASE RETURNS
    $rs = mysqli_query($connection,
        "SELECT date_time date, discount_amount amount, paid_by, r_inv_id invoice,
         SUM(product_quantity) total_qty
         FROM purchase
         WHERE customer_name='$supplier'
         AND status='return'
         AND date_time BETWEEN '$startDate' AND '$endDate'
         GROUP BY r_inv_id"
    );
    while ($r = mysqli_fetch_assoc($rs)) {
        $transactions[] = [
            'date' => $r['date'],
            'description' => 'Purchase Return',
            'amount' => -abs($r['amount']),
            'paid_by' => $r['paid_by'],
            'total_qty' => $r['total_qty'],
            'invoice' => $r['invoice']
        ];
    }

    usort($transactions, fn($a,$b)=>strtotime($a['date'])<=>strtotime($b['date']));
}

/* ================= SUPPLIER INFO ================= */
$supplierInfo = [];
if ($supplier) {
    $rs = mysqli_query($connection,
        "SELECT supplier_id, supplier_name, supplier_company, supplier_phone
         FROM supplier WHERE supplier_name='$supplier' LIMIT 1"
    );
    if ($rs && mysqli_num_rows($rs)) {
        $supplierInfo = mysqli_fetch_assoc($rs);
    }
}

// --- Payment Method Mapping ---
$methodNames = [
    'cash'   => 'Cash',
    'bank1'  => 'Ibrahim Meezan',
    'bank2'  => 'Adil Meezan',
    'bank3'  => 'HBL Bank',
    'bank4'  => 'JazzCash',
    'other'  => 'Other'
];
?>
<!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>
    
    <style>
        body {
            font-family: 'Quicksand', sans-serif;
        }
        .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;
        }	 
        .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;
        }
        .fa-download:hover{
            color:#953E39;
        }
        .btn, .form-control, option, tr{
            font-weight:700;
        }
        p{
            color:#000;
        }
    </style>
</head>

<body id="page-top">
    <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">
                    <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 mt-5">
                    <div class="row">
                        <div class="col-sm-5">
                            <h3 style="color:#060606; font-weight:700;">Supplier Ledger Report</h3>
                        </div>
                        
                    </div>
                    <br>
                    
                    <form method="post">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="supplier">Supplier Company:</label>
                                    <select class="form-control" name="supplier" required>
                                        <option value="">Select Supplier</option>
                                        <?php
                                        $supplierQuery = "SELECT DISTINCT supplier_name FROM supplier ORDER BY supplier_name ASC";
                                        $supplierResult = mysqli_query($connection, $supplierQuery);
                                        if ($supplierResult && mysqli_num_rows($supplierResult) > 0) {
                                            while ($row = mysqli_fetch_assoc($supplierResult)) {
                                                $selected = ($row['supplier_name'] == $supplier) ? 'selected' : '';
                                                echo "<option value='" . htmlspecialchars($row['supplier_name']) . "' $selected>" . htmlspecialchars($row['supplier_name']) . "</option>";
                                            }
                                        }
                                        ?>
                                    </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); ?>" required>
                                </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); ?>" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <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_supplier.php">
                                        <button type="button" 
                                        class="btn btn-dark btn-lg" style="margin-top:30px;">
                                            <i class="fas fa-sync-alt fa-1x"></i></button></a>
                                    <button id="downloadExcel" 
                                    class="btn btn-success" style="margin-top:30px;">Excel</button>
                                    <button id="downloadPdf" type="button" 
                                    class="btn btn-danger" style="margin-top:30px;">PDF</button>
                                </div>
                            </div>
                        </div>
                    </form>

                    <br>
                    
                    <div id="table-container-wrapper">
                        <?php if (isset($transactions)): ?>
                            
                            <?php if (!empty($supplierInfo)): ?>
                            <table class="table table-bordered shadow-sm bg-white">
                                <thead style="background:#0A4657; color:white;">
                                    <tr>
                                        <th colspan="4" class="text-center">Supplier Information</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <th colspan="4" class="text-center">Report Date: <?php echo $startDate.' To '.$endDate ?></th>
                                    </tr>
                                    <tr>
                                        <th style="width:30%;">Supplier ID</th>
                                        <td><?= htmlspecialchars($supplierInfo['supplier_id'] ?? '') ?></td>
                                        <th>Phone</th>
                                        <td><?= htmlspecialchars($supplierInfo['supplier_phone'] ?? 'N/A') ?></td>
                                    </tr>
                                    <tr>
                                        <th>Company Name</th>
                                        <td><?= htmlspecialchars($supplierInfo['supplier_company'] ?? '') ?></td>
                                        <th>Contact Person</th>
                                        <td><?= htmlspecialchars($supplierInfo['supplier_name'] ?? 'N/A') ?></td>
                                    </tr>
                                   
                                </tbody>
                            </table>
                            <?php endif; ?>

                            <div class="col-sm-12">
                                <table id="patientTable" class="table table-striped table-hover text-center table-sm bg-white">
                                    <thead>
                                        <tr class="bg-dark text-white">
                                            <th>Date</th>
                                            <th>Head</th>
                                            <th>Quantity</th>
                                            <th>Description</th>
                                            <th>Invoice No.</th>
                                            <th>Paid By</th>
                                            <th>Debit Amount (Rs)</th>
                                            <th>Credit Amount (Rs)</th>
                                            <th>Balance (Rs)</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Opening Balance Row -->
                                        <tr>
                                            <td style="color:#0A4657; font-weight:700;"><?= htmlspecialchars($startDate) ?></td>
                                            <td style="color:#0A4657; font-weight:700;">Opening Balance</td>
                                            <td>-</td>
                                            <td>-</td>
                                            <td></td>
                                            <td></td>
                                            <!-- Debit -->
                                            <td style="color:#0A4657; font-weight:700;">
                                                <?= $openingBalance > 0 ? number_format($openingBalance, 2) : '' ?>
                                            </td>
                                            <!-- Credit -->
                                            <td style="color:#0A4657; font-weight:700;">
                                                <?= $openingBalance < 0 ? number_format(abs($openingBalance), 2) : '' ?>
                                            </td>
                                            <!-- Balance -->
                                            <td style="color:#0A4657; font-weight:700;">
                                                <?= number_format($openingBalance, 2) ?>
                                            </td>
                                        </tr>

                                        <?php 
                                        $totalQuantity = 0;
                                        foreach ($transactions as $transaction): 
                                            $positiveAmount = '';
                                            $negativeAmount = '';

                                            if ($transaction['amount'] > 0) {
                                                $balance += $transaction['amount'];
                                                $positiveAmount = number_format($transaction['amount'], 2);
                                            } else {
                                                $balance += $transaction['amount'];
                                                $negativeAmount = number_format(abs($transaction['amount']), 2);
                                            }

                                            if (!empty($transaction['total_qty']) && $transaction['total_qty'] > 0) {
                                                $totalQuantity += $transaction['total_qty'];
                                            }

                                            $description = $transaction['desc_name'] ?? '-';

                                            // Map payment method
                                            $rawPaidBy = $transaction['paid_by'];
                                            $normalizedKey = strtolower(trim($rawPaidBy));
                                            $displayMethod = $methodNames[$normalizedKey] ?? ucfirst($rawPaidBy);
                                        ?>
                                        <tr style="color:#060606;">
                                            <td><?= htmlspecialchars($transaction['date']) ?></td>
                                            <td><?= htmlspecialchars($transaction['description']) ?></td>
                                            <td>
                                                <?php 
                                                if ($transaction['total_qty'] > 0) {
                                                    echo number_format($transaction['total_qty'], 0);
                                                } else {
                                                    echo '-';
                                                }
                                                ?>
                                            </td>
                                            <td><?= htmlspecialchars($description) ?></td>
                                            <td><?= htmlspecialchars($transaction['invoice']) ?></td>
                                            <!-- Updated: use mapped value -->
                                            <td><?= htmlspecialchars($displayMethod) ?></td>
                                            <td><?= $positiveAmount ?></td>
                                            <td><?= $negativeAmount ?></td>
                                            <td><?= number_format($balance, 2) ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>

                                <table class="table bg-white">
                                    <tfoot>
                                        <tr>
                                            <th>Total Quantity:</th>
                                            <td><?= number_format($totalQuantity, 0) ?></td>
                                        </tr>
                                        <tr>
                                            <th>Final Balance:</th>
                                            <td><?= number_format($balance, 2) ?></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <!-- /.container-fluid -->
            </div>
            <!-- 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</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <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 src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>

    <script>
document.getElementById("downloadPdf").addEventListener("click", async function () {

    // ✅ FIX 1: Correct jsPDF initialization
    const { jsPDF } = window.jspdf;

    // ✅ FIX 2: Define formattedDateTime
    const now = new Date();
    const formattedDateTime = now.toLocaleDateString() + " " + now.toLocaleTimeString();

    const report = document.getElementById("table-container-wrapper");
    if (!report) {
        alert("Table not found!");
        return;
    }

    try {
        const canvas = await html2canvas(report, { scale: 2 });
        const imgData = canvas.toDataURL("image/jpeg", 0.65);

        const pdf = new jsPDF("p", "mm", "a4");

        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();

        const imgWidth = pageWidth - 10;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        let y = 30;

        /* HEADER */
        pdf.setFont("helvetica", "bold");
        pdf.setFontSize(16);
        pdf.text("Whole Sale Retail", 2, 12);
        pdf.text("Supplier Ledger Report", pageWidth - 2, 12, { align: "right" });

        pdf.setFont("helvetica", "normal");
        pdf.setFontSize(10);
        pdf.text("Address: Al-Hafeez Shopping Mall, Gulberg III Lahore.", 2, 18);
        pdf.text("Phone: 0334-8739892, Whatsapp: 0334-8739892", 2, 22);
        pdf.text("Email: info@atrsms.pk", 2, 26);

        pdf.setFont("helvetica", "bold");
        pdf.text(`Printed: ${formattedDateTime}`, pageWidth - 2, 22, { align: "right" });

        pdf.addImage(imgData, "JPEG", 5, y, imgWidth, imgHeight);

        let heightLeft = imgHeight;

        while (heightLeft > pageHeight - 20) {
            heightLeft -= pageHeight;
            pdf.addPage();
            pdf.addImage(imgData, "JPEG", 5, 10 - heightLeft, imgWidth, imgHeight);
        }

        pdf.save("Supplier-Ledger-Report.pdf");

    } catch (error) {
        console.error(error);
        alert("PDF generation failed");
    }
});
</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>