<?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 ================= */
$creditor = '';
$startDate = '';
$endDate = '';
$transactions = [];
$openingBalance = 0;
$balance = 0;

/* ================= FILTER ================= */
if (isset($_POST['filter'])) {

    $creditor  = 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 creditor_opening_amount
         WHERE creditor_name='$creditor' LIMIT 1"
    );
    if ($res && mysqli_num_rows($res)) {
        $baseOpening = (float)mysqli_fetch_assoc($res)['open_amount'];
    }

    /* ===== TRANSACTIONS BEFORE START DATE ===== */
    // Credit sales before start date
    $q1 = "SELECT COALESCE(SUM(order_total),0) total FROM (
                SELECT order_id, MAX(discount_amount) AS order_total
                FROM log_user_sales
                WHERE customer_name='$creditor'
                AND paid_by='credit'
                AND status!='refund'
                AND date_time < '$startDate'
                GROUP BY order_id
            ) t";
    $res1 = mysqli_query($connection, $q1);
    if (!$res1) {
        die("Error in credit sales before query: " . mysqli_error($connection));
    }
    $creditSalesBefore = mysqli_fetch_assoc($res1)['total'];

    // Refunds before start date
    $q2 = "SELECT COALESCE(SUM(order_total),0) total FROM (
                SELECT r_order_id, MAX(discount_amount) AS order_total
                FROM log_user_sales
                WHERE customer_name='$creditor'
                AND paid_by='credit'
                AND status='refund'
                AND date_time < '$startDate'
                GROUP BY r_order_id
            ) t";
    $res2 = mysqli_query($connection, $q2);
    if (!$res2) {
        die("Error in refunds before query: " . mysqli_error($connection));
    }
    $refundsBefore = mysqli_fetch_assoc($res2)['total'];

    // Credit paid before start date
    $q3 = "SELECT COALESCE(SUM(amount),0) total
           FROM credit_paid
           WHERE cr_name='$creditor'
           AND date_time < '$startDate'";
    $res3 = mysqli_query($connection, $q3);
    if (!$res3) {
        die("Error in credit paid before query: " . mysqli_error($connection));
    }
    $creditPaidBefore = mysqli_fetch_assoc($res3)['total'];

    /* ===== FINAL OPENING BALANCE ===== */
    $openingBalance =
        $baseOpening
        + $creditSalesBefore
        - $refundsBefore
        - $creditPaidBefore;

    $balance = $openingBalance;

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

    // CREDIT SALES (with extra charges added individually, not SUM)
    $q4 = "SELECT date_time date,
                (MAX(discount_amount) + MAX(cutting) + MAX(ctn) + MAX(bora) + MAX(vehicle_rent) + MAX(loading)) AS amount,
                paid_by, order_id,
                SUM(product_quantity) total_qty,
                GROUP_CONCAT(DISTINCT product_name SEPARATOR ', ') product_name,
                GROUP_CONCAT(DISTINCT desc_note SEPARATOR ', ') desc_note,
                (MAX(cutting) + MAX(ctn) + MAX(bora) + MAX(vehicle_rent) + MAX(loading)) AS other_exp
         FROM log_user_sales
         WHERE customer_name='$creditor'
         AND paid_by='credit'
         AND status!='refund'
         AND date_time BETWEEN '$startDate' AND '$endDate'
         GROUP BY order_id";
    $res4 = mysqli_query($connection, $q4);
    if (!$res4) {
        die("Error in credit sales query: " . mysqli_error($connection));
    }
    while ($r = mysqli_fetch_assoc($res4)) {
        // paid_by here is always 'credit', no mapping needed but we keep it safe
        $paid_by_display = isset($bank_map[$r['paid_by']]) ? $bank_map[$r['paid_by']] : $r['paid_by'];
        $transactions[] = [
            'date'        => $r['date'],
            'description' => 'Credit Sale',
            'amount'      => $r['amount'],
            'paid_by'     => $paid_by_display,
            'total_qty'   => $r['total_qty'],
            'invoice'     => $r['order_id'],
            'product_name'=> $r['product_name'],
            'desc_note'   => $r['desc_note'],
            'other_exp'   => $r['other_exp']
        ];
    }

    // POS CASH (same logic – other expenses as MAX)
    $q5 = "SELECT date_time date,
                cash_amount amount,
                paid_by, order_id,
                SUM(product_quantity) total_qty,
                GROUP_CONCAT(DISTINCT product_name SEPARATOR ', ') product_name,
                GROUP_CONCAT(DISTINCT desc_note SEPARATOR ', ') desc_note,
                (MAX(cutting) + MAX(ctn) + MAX(bora) + MAX(vehicle_rent) + MAX(loading)) AS other_exp
         FROM log_user_sales
         WHERE customer_name='$creditor'
         AND paid_by='pos'
         AND status!='refund'
         AND date_time BETWEEN '$startDate' AND '$endDate'
         GROUP BY order_id";
    $res5 = mysqli_query($connection, $q5);
    if (!$res5) {
        die("Error in POS cash query: " . mysqli_error($connection));
    }
    while ($r = mysqli_fetch_assoc($res5)) {
        $paid_by_display = isset($bank_map[$r['paid_by']]) ? $bank_map[$r['paid_by']] : $r['paid_by'];
        $transactions[] = [
            'date'        => $r['date'],
            'description' => 'POS Cash Received',
            'amount'      => $r['amount'],
            'paid_by'     => $paid_by_display,
            'total_qty'   => $r['total_qty'],
            'invoice'     => $r['order_id'],
            'product_name'=> $r['product_name'],
            'desc_note'   => $r['desc_note'],
            'other_exp'   => $r['other_exp']
        ];
    }

    // REFUNDS (no extra charges)
    $q6 = "SELECT date_time date, discount_amount amount, paid_by, r_order_id invoice
         FROM log_user_sales
         WHERE customer_name='$creditor'
         AND status='refund'
         AND paid_by='credit'
         AND date_time BETWEEN '$startDate' AND '$endDate'
         GROUP BY r_order_id";
    $res6 = mysqli_query($connection, $q6);
    if (!$res6) {
        die("Error in refunds query: " . mysqli_error($connection));
    }
    while ($r = mysqli_fetch_assoc($res6)) {
        $paid_by_display = isset($bank_map[$r['paid_by']]) ? $bank_map[$r['paid_by']] : $r['paid_by'];
        $transactions[] = [
            'date'        => $r['date'],
            'description' => 'Credit Sale Return',
            'amount'      => -abs($r['amount']),
            'paid_by'     => $paid_by_display,
            'total_qty'   => 0,
            'invoice'     => $r['invoice'],
            'product_name'=> '-',
            'desc_note'   => '-',
            'other_exp'   => 0
        ];
    }

    // CREDIT RECEIVED
    $q7 = "SELECT date_time date, amount, paid_by
         FROM credit_paid
         WHERE cr_name='$creditor'
         AND date_time BETWEEN '$startDate' AND '$endDate'";
    $res7 = mysqli_query($connection, $q7);
    if (!$res7) {
        die("Error in credit received query: " . mysqli_error($connection));
    }
    while ($r = mysqli_fetch_assoc($res7)) {
        // Map bank codes to full names here
        $paid_by_display = isset($bank_map[$r['paid_by']]) ? $bank_map[$r['paid_by']] : $r['paid_by'];
        $transactions[] = [
            'date'        => $r['date'],
            'description' => 'Credit Received',
            'amount'      => -abs($r['amount']),
            'paid_by'     => $paid_by_display,
            'total_qty'   => 0,
            'invoice'     => '-',
            'product_name'=> '-',
            'desc_note'   => '-',
            'other_exp'   => 0
        ];
    }

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

/* ================= CUSTOMER INFO ================= */
$customerInfo = [];
if ($creditor) {
    $q8 = "SELECT cr_name, cr_address, phone_number, cr_id
         FROM credit_note WHERE cr_name='$creditor' LIMIT 1";
    $res8 = mysqli_query($connection, $q8);
    if ($res8 && mysqli_num_rows($res8)) {
        $customerInfo = mysqli_fetch_assoc($res8);
    }
}
?>


<!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">
    <title><?php echo $tx ?></title>

    <!-- Stylesheets -->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
    <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; }
        .btn, .form-control, option, tr { font-weight: 700; }
        p { color: #000; }
    </style>
</head>

<body id="page-top">
    <div id="wrapper">
        <?php include("common/sd.php"); ?>

        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <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>

                <div class="container-fluid mt-5">
                    <div class="row">
                        <div class="col-sm-5">
                            <h3 style="color:#060606; font-weight:700;">Customer Ledger Report</h3>
                        </div>
                        <div class="col-sm-4"></div>
                        <div class="col-sm-3"></div>
                    </div>
                    <br>

                    <?php
                    $creditorQuery = "SELECT DISTINCT cr_name FROM credit_note ORDER BY cr_name ASC";
                    $creditorResult = mysqli_query($connection, $creditorQuery);
                    ?>

                    <form method="post">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="supplier">Customer Name:</label>
                                    <select class="form-control" name="supplier" required>
                                        <option value="">Select Customer</option>
                                        <?php
                                        if ($creditorResult && mysqli_num_rows($creditorResult) > 0) {
                                            while ($row = mysqli_fetch_assoc($creditorResult)) {
                                                $selected = ($row['cr_name'] == $creditor) ? 'selected' : '';
                                                echo "<option value='" . htmlspecialchars($row['cr_name']) . "' $selected>" . htmlspecialchars($row['cr_name']) . "</option>";
                                            }
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="startDate">Start Date:</label>
                                    <input type="date" class="form-control" name="startDate" value="<?= htmlspecialchars($_POST['startDate'] ?? '') ?>" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="endDate">End Date:</label>
                                    <input type="date" class="form-control" name="endDate" value="<?= htmlspecialchars($_POST['endDate'] ?? '') ?>" required>
                                </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_recieve.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 (!empty($transactions)): ?>
                            <?php if (!empty($customerInfo)): ?>
                            <table class="table table-bordered shadow-sm bg-white">
                                <thead style="background:#0A4657; color:white;">
                                    <tr><th colspan="4" class="text-center">Customer Information</th></tr>
                                </thead>
                                <tbody>
                                    <tr><th colspan="4" class="text-center">Report Date: <?= $startDate ?> To <?= $endDate ?></th></tr>
                                    <tr><th style="width:30%;">ID</th><td><?= htmlspecialchars($customerInfo['cr_id'] ?? '') ?></td>
                                        <th>Name:</th><td><?= htmlspecialchars($customerInfo['cr_name'] ?? '') ?></td></tr>
                                    <tr><th>Phone:</th><td><?= htmlspecialchars($customerInfo['phone_number'] ?? 'N/A') ?></td>
                                        <th>Address:</th><td><?= htmlspecialchars($customerInfo['cr_address'] ?? '') ?></td></tr>
                                </tbody>
                            </table>
                            <?php endif; ?>

                            <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>
                                    <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>
                                        <td style="color:#0A4657; font-weight:700;">
                                            <?= $openingBalance > 0 ? number_format($openingBalance, 2) : '' ?>
                                        </td>
                                        <td style="color:#0A4657; font-weight:700;">
                                            <?= $openingBalance < 0 ? number_format(abs($openingBalance), 2) : '' ?>
                                        </td>
                                        <td style="color:#0A4657; font-weight:700;">
                                            <?= number_format($openingBalance, 2) ?>
                                        </td>
                                    </tr>

                                    <?php $totalQuantity = 0; ?>
                                    <?php foreach ($transactions as $transaction): ?>
                                        <?php 
                                        $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'];
                                        }
                                        ?>
                                        <tr style="color:#060606;">
                                            <td><?= htmlspecialchars($transaction['date']) ?></td>
                                            <td><?= htmlspecialchars($transaction['description']) ?></td>
                                            <td><?= htmlspecialchars($transaction['product_name']) ?></td>
                                            <td><?= ($transaction['total_qty'] > 0) ? number_format($transaction['total_qty'], 0) : '-' ?></td>
                                            <td><?= ($transaction['other_exp'] > 0) ? number_format($transaction['other_exp'], 2) : '-' ?></td>
                                            <td><?= htmlspecialchars($transaction['desc_note']) ?></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>
                        <?php endif; ?>
                    </div>
                    <br><br>
                </div>
            </div>
            <?php include("common/main_ft.php"); ?>
        </div>
    </div>

    <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">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>

    <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>
        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, useCORS: true });
                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 position = 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.setFont("helvetica", "bold");
                pdf.text(`Printed: ${formattedDateTime}`, pageWidth - 2, 22, { align: "right" });
                pdf.addImage(imgData, "JPEG", 5, position, imgWidth, imgHeight);
                let heightLeft = imgHeight;
                while (heightLeft > pageHeight - 20) {
                    heightLeft -= pageHeight;
                    pdf.addPage();
                    pdf.addImage(imgData, "JPEG", 5, 10 - heightLeft, imgWidth, imgHeight);
                }
                pdf.save("Customer-Ledger-Report.pdf");
            } catch (error) {
                console.error(error);
                alert("PDF generation failed");
            }
        });
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>
    <script>
        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: "Customers" });
            try { XLSX.writeFile(workbook, 'Customer_Ledger.xlsx'); }
            catch (error) { alert("Error generating Excel file."); }
        });
    </script>
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
    <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>