<?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'];

/* ================= BANK MAPPING ================= */
$bank_map = [
    'bank1' => 'Meezan Bank',
    'bank2' => 'Faysal Bank',
    'bank3' => 'Bank AL-Habib'
];

/* ================= 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 (extra charges with MAX)
    $q1 = "SELECT COALESCE(SUM(order_total),0) total 
           FROM (
               SELECT inv_id, 
                      (MAX(discount_amount) + MAX(cutting) + MAX(ctn) + MAX(bora) + MAX(vehicle_rent) + MAX(loading)) AS order_total
               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";
    $res1 = mysqli_query($connection, $q1);
    if (!$res1) die("Error in credit purchases before query: " . mysqli_error($connection));
    $creditPurchasesBefore = mysqli_fetch_assoc($res1)['total'];

    // Purchase Returns BEFORE start date
    $q2 = "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";
    $res2 = mysqli_query($connection, $q2);
    if (!$res2) die("Error in purchase returns before query: " . mysqli_error($connection));
    $purchaseReturnsBefore = mysqli_fetch_assoc($res2)['total'];

    // Payments to supplier BEFORE start date
    $q3 = "SELECT COALESCE(SUM(supplier_amount),0) total
           FROM supplier_paid
           WHERE supplier_name='$supplier'
           AND date_time < '$startDate'";
    $res3 = mysqli_query($connection, $q3);
    if (!$res3) die("Error in payments before query: " . mysqli_error($connection));
    $paymentsBefore = mysqli_fetch_assoc($res3)['total'];

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

    $balance = $openingBalance;

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

    // CREDIT PURCHASES (amount includes extra charges with MAX)
    $q4 = "SELECT date_time date,
                  (MAX(discount_amount) + MAX(cutting) + MAX(ctn) + MAX(bora) + MAX(vehicle_rent) + MAX(loading)) AS amount,
                  paid_by, inv_id,
                  SUM(product_quantity) total_qty,
                  GROUP_CONCAT(DISTINCT product_name SEPARATOR ', ') product_name,
                  (MAX(cutting) + MAX(ctn) + MAX(bora) + MAX(vehicle_rent) + MAX(loading)) AS other_exp,
                  GROUP_CONCAT(DISTINCT desc_note SEPARATOR ', ') desc_note
           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";
    $res4 = mysqli_query($connection, $q4);
    if (!$res4) die("Error in credit purchases query: " . mysqli_error($connection));
    while ($r = mysqli_fetch_assoc($res4)) {
        $transactions[] = [
            'date'         => $r['date'],
            'description'  => 'Credit Purchase',
            'amount'       => $r['amount'],
            'paid_by'      => $r['paid_by'], // This is always "Credit", no mapping needed
            'total_qty'    => $r['total_qty'],
            'invoice'      => $r['inv_id'],
            'product_name' => $r['product_name'],
            'other_exp'    => $r['other_exp'],
            'desc_note'    => $r['desc_note']
        ];
    }

    // PAYMENTS TO SUPPLIER
    $q5 = "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'";
    $res5 = mysqli_query($connection, $q5);
    if (!$res5) die("Error in payments query: " . mysqli_error($connection));
    while ($r = mysqli_fetch_assoc($res5)) {
        // Apply bank mapping
        $paidByDisplay = isset($bank_map[$r['paid_by']]) ? $bank_map[$r['paid_by']] : ucfirst($r['paid_by']);
        $transactions[] = [
            'date'         => $r['date'],
            'description'  => 'Payment to Supplier',
            'amount'       => -abs($r['amount']),
            'paid_by'      => $paidByDisplay,
            'total_qty'    => 0,
            'invoice'      => '-',
            'product_name' => '',
            'other_exp'    => 0,
            'desc_note'    => $r['description']
        ];
    }

    // PURCHASE RETURNS (extra charges with MAX)
    $q6 = "SELECT date_time date, discount_amount amount, paid_by, r_inv_id invoice,
                  SUM(product_quantity) total_qty,
                  GROUP_CONCAT(DISTINCT product_name SEPARATOR ', ') product_name,
                  (MAX(cutting) + MAX(ctn) + MAX(bora) + MAX(vehicle_rent) + MAX(loading)) AS other_exp,
                  GROUP_CONCAT(DISTINCT desc_note SEPARATOR ', ') desc_note
           FROM purchase
           WHERE customer_name='$supplier'
           AND status='return'
           AND date_time BETWEEN '$startDate' AND '$endDate'
           GROUP BY r_inv_id";
    $res6 = mysqli_query($connection, $q6);
    if (!$res6) die("Error in purchase returns query: " . mysqli_error($connection));
    while ($r = mysqli_fetch_assoc($res6)) {
        // Apply bank mapping if paid_by is a bank code
        $paidByDisplay = isset($bank_map[$r['paid_by']]) ? $bank_map[$r['paid_by']] : $r['paid_by'];
        $transactions[] = [
            'date'         => $r['date'],
            'description'  => 'Purchase Return',
            'amount'       => -abs($r['amount']),
            'paid_by'      => $paidByDisplay,
            'total_qty'    => $r['total_qty'],
            'invoice'      => $r['invoice'],
            'product_name' => $r['product_name'],
            'other_exp'    => $r['other_exp'],
            'desc_note'    => $r['desc_note']
        ];
    }

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

/* ================= SUPPLIER INFO ================= */
$supplierInfo = [];
if ($supplier) {
    $q7 = "SELECT supplier_id, supplier_name, supplier_company, supplier_phone
           FROM supplier WHERE supplier_name='$supplier' LIMIT 1";
    $res7 = mysqli_query($connection, $q7);
    if ($res7 && mysqli_num_rows($res7)) {
        $supplierInfo = mysqli_fetch_assoc($res7);
    }
}
?>
<!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;">Party Ledger Report</h3>
                        </div>
                    </div>
                    <br>
                    
                    <form method="post">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="supplier">Party Company:</label>
                                    <select class="form-control" name="supplier" required>
                                        <option value="">Select Party</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>Product Name</th>
                                            <th>Quantity</th>
                                            <th>Other Exp</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>
                                            <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'];
                                            }

                                            $productName = $transaction['product_name'] ?: '-';
                                            $otherExp    = ($transaction['other_exp'] > 0) ? number_format($transaction['other_exp'], 2) : '-';
                                            $descNote    = $transaction['desc_note'] ?: '-';
                                        ?>
                                        <tr style="color:#060606;">
                                            <td><?= htmlspecialchars($transaction['date']) ?></td>
                                            <td><?= htmlspecialchars($transaction['description']) ?></td>
                                            <td><?= htmlspecialchars($productName) ?></td>
                                            <td><?= ($transaction['total_qty'] > 0) ? number_format($transaction['total_qty'], 0) : '-' ?></td>
                                            <td><?= $otherExp ?></td>
                                            <td><?= htmlspecialchars($descNote) ?></td>
                                            <td><?= htmlspecialchars($transaction['invoice']) ?></td>
                                            <td><?= ucfirst(htmlspecialchars($transaction['paid_by'])) ?></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 () {
            const { jsPDF } = window.jspdf;
            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;

                pdf.setFont("helvetica", "bold");
                pdf.setFontSize(16);
                  pdf.text("BSL Steel Traders Karachi", 2, 12);
        pdf.setFont("helvetica", "normal");
        pdf.setFontSize(10);
        pdf.text("Address: Shop No 82 ", 2, 17);
        pdf.setFontSize(10);
        pdf.text("Phone: 03212121294. 03362121292", 2, 21);
        pdf.setFontSize(10);
                pdf.text("", 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");
            }
        });

        document.getElementById('downloadExcel').addEventListener('click', function() {
            var table = document.getElementById('patientTable');
            var clone = table.cloneNode(true);
            var rows = clone.querySelectorAll('tr');
            rows.forEach(function(row) {
                if (row.style.display === 'none' || row.innerText.trim() === '') {
                    row.remove();
                }
            });
            var workbook = XLSX.utils.table_to_book(clone, { sheet: "Supplier Ledger" });
            try {
                XLSX.writeFile(workbook, 'Supplier_Ledger.xlsx');
            } catch (error) {
                console.error("Error while writing the file: ", error);
                alert("Error generating Excel file.");
            }
        });
    </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>

    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>