<?php
include "db.php";
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

$reference_type = $_GET['type'] ?? 'customer';
$reference_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!in_array($reference_type, ['customer', 'supplier'])) {
    die("Invalid reference type");
}

$ref_table = ($reference_type === 'customer') ? 'customers' : 'suppliers';

/* GET FIRST ID IF EMPTY */
if (!$reference_id) {
    $first = $conn->query("SELECT id FROM $ref_table ORDER BY id ASC LIMIT 1");
    if($first && $first->num_rows > 0){
        $reference_id = $first->fetch_assoc()['id'];
    }
}

/* NAME */
$ref_name = "Unknown";
$stmt = $conn->prepare("SELECT name FROM $ref_table WHERE id = ?");
$stmt->bind_param('i', $reference_id);
$stmt->execute();
$stmt->bind_result($ref_name);
$stmt->fetch();
$stmt->close();

/* OPENING BALANCE */
$opening_balance = 0;
$stmt_open = $conn->prepare("SELECT opening_balance FROM $ref_table WHERE id = ?");
$stmt_open->bind_param('i', $reference_id);
$stmt_open->execute();
$stmt_open->bind_result($opening_balance);
$stmt_open->fetch();
$stmt_open->close();

/* TRANSACTIONS */
$data = [];
$stmt = $conn->prepare("
    SELECT 
        id, 
        reference_id,
        voucher_id,
        date,
        description,
        type,
        amount
    FROM transactions 
    WHERE reference_id = ? 
    AND reference_type = ?
    ORDER BY date ASC, id ASC
");
$stmt->bind_param('is', $reference_id, $reference_type);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
    $data[] = $row;
}
$stmt->close();

/* RUNNING BALANCE */
$running_balance = (float)$opening_balance;
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= ucfirst($reference_type); ?> Ledger - Tameer Al Madina</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

<style>
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    background: #F4F6F9;
    font-family: 'Poppins', sans-serif;
    min-height: 100vh;
    overflow-y: auto;
}

.main-layout {
    display: flex;
    width: 100%;
    min-height: 100vh;
    position: relative;
}

/* Master Fixed Left Sidebar Layout */
aside, .sidebar, [class*="sidebar"] {
    width: 260px;
    min-width: 260px;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
    transition: all 0.3s ease;
}

.content-wrapper {
    flex: 1;
    margin-left: 260px;
    display: flex;
    flex-direction: column;
    background: #F4F6F9;
    min-width: 0;
    width: calc(100% - 260px);
    transition: all 0.3s ease;
}

/* System Top Headers Section */
.top-navbar {
    height: 60px;
    background: #FFFFFF;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30px;
    border-bottom: 1px solid #EAEAEA;
}

.navbar-left-flex {
    display: flex;
    align-items: center;
    gap: 15px;
}

.mobile-menu-toggle {
    display: none;
    font-size: 20px;
    color: #0A192F;
    cursor: pointer;
    background: #F4F6F9;
    width: 38px;
    height: 38px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    border: 1px solid #E2E8F0;
}

.search-container {
    position: relative;
    width: 300px;
}

.search-container input {
    width: 100%;
    padding: 8px 15px 8px 40px;
    background: #F8F9FA;
    border: 1px solid #E2E8F0;
    border-radius: 8px;
    font-size: 13px;
    outline: none;
}

.search-container i {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    color: #A0AEC0;
}

.user-profile {
    display: flex;
    align-items: center;
    gap: 20px;
}

.profile-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.profile-info i.profile-icon {
    font-size: 26px;
    color: #4A5568;
    background: #F4F6F9;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    border: 1px solid #E2E8F0;
}

.profile-text h4 {
    font-size: 13px;
    color: #1A202C;
    font-weight: 600;
}

.profile-text p {
    font-size: 11px;
    color: #718096;
}

/* Page Fluid Workspace Content */
.page-container {
    padding: 20px 30px;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.form-card {
    background: #FFFFFF;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    width: 100%;
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
}

.form-banner {
    background: linear-gradient(135deg, #0A192F 0%, #172A45 100%);
    padding: 15px 30px;
    color: #FFFFFF;
    border-bottom: 4px solid #0d6efd;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.banner-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.banner-icon {
    background: rgba(255, 255, 255, 0.1);
    width: 38px;
    height: 38px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    font-size: 16px;
}

.banner-text h2 {
    font-size: 18px;
    font-weight: 600;
}

.banner-text p {
    font-size: 11px;
    color: #A0AEC0;
}

/* Share and Download Action Buttons Elements */
.banner-actions {
    display: flex;
    gap: 10px;
}

.btn-action {
    padding: 8px 14px;
    font-size: 12px;
    font-weight: 500;
    border-radius: 6px;
    border: none;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    text-decoration: none;
    color: #FFFFFF;
    transition: opacity 0.2s;
    font-family: 'Poppins', sans-serif;
}

.btn-action:hover {
    opacity: 0.9;
}

.btn-print { background-color: #4A5568; }
.btn-pdf { background-color: #E53E3E; }
.btn-whatsapp { background-color: #25D366; }

/* Operational Filter Inputs Panel */
.filter-box {
    background: #F8FAFC;
    padding: 15px 30px;
    border-bottom: 1px solid #E2E8F0;
    display: flex;
    gap: 20px;
    align-items: center;
    flex-wrap: wrap;
}

.filter-group {
    display: flex;
    align-items: center;
    gap: 10px;
}

.filter-box label {
    font-size: 12px;
    font-weight: 600;
    color: #4A5568;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.filter-box select {
    padding: 8px 14px;
    border: 1px solid #CBD5E1;
    border-radius: 6px;
    background: #FFFFFF;
    color: #1A202C;
    font-size: 13px;
    font-family: 'Poppins', sans-serif;
    outline: none;
    min-width: 160px;
    cursor: pointer;
    transition: border-color 0.2s;
}

.filter-box select:focus {
    border-color: #0d6efd;
}

/* Master Data Grid Setup (Desktop) */
.table-responsive {
    width: 100%;
    overflow-x: auto;
}

table {
    width: 100%;
    border-collapse: collapse;
}

table thead {
    background: #F1F5F9;
    border-bottom: 2px solid #E2E8F0;
}

table th {
    padding: 14px 20px;
    font-size: 12px;
    font-weight: 600;
    color: #4A5568;
    text-align: left;
}

table td {
    padding: 12px 20px;
    border-bottom: 1px solid #E2E8F0;
    font-size: 13px;
    color: #4A5568;
    background: #FFFFFF;
    vertical-align: middle;
}

table tbody tr:hover td {
    background: #F8FAFC;
}

/* Statement Status Ledger Elements */
.debit {
    color: #DC3545;
    font-weight: 600;
}

.credit {
    color: #28A745;
    font-weight: 600;
}

.balance {
    font-weight: 600;
    color: #0A192F;
}

.ledger-link {
    color: #0d6efd;
    text-decoration: none;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 5px;
}

.ledger-link:hover {
    text-decoration: underline;
    color: #0a58ca;
}

/* Mobile Fluid Cards Architecture */
.mobile-cards-container {
    display: none;
    padding: 15px;
    background: #F8F9FA;
    flex-direction: column;
    gap: 12px;
}

.mobile-card {
    background: #FFFFFF;
    border-radius: 8px;
    padding: 15px;
    border: 1px solid #E2E8F0;
    box-shadow: 0 2px 5px rgba(0,0,0,0.02);
}

.card-header-flex {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    border-bottom: 1px dashed #E2E8F0;
    padding-bottom: 8px;
    margin-bottom: 10px;
}

.card-title-area h3 {
    font-size: 13px;
    color: #0A192F;
    font-weight: 500;
    line-height: 1.4;
}

.card-title-area span {
    font-size: 11px;
    color: #A0AEC0;
    display: block;
    margin-top: 2px;
}

.detail-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 6px;
    font-size: 12px;
}

.detail-row .label {
    color: #718096;
}

.detail-row .value {
    font-weight: 500;
}

.no-data {
    text-align: center;
    padding: 40px !important;
    color: #A0AEC0;
    font-size: 14px;
}

.no-data i {
    font-size: 24px;
    margin-bottom: 8px;
    display: block;
    color: #CBD5E1;
}

.sidebar-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.4);
    z-index: 998;
}

@media (min-width: 992px) {
    body { overflow-y: auto !important; }
    .page-container { min-height: calc(100vh - 60px); }
}

@media (max-width: 1024px) and (min-width: 769px) {
    aside, .sidebar, [class*="sidebar"] { width: 240px; min-width: 240px; }
    .content-wrapper { margin-left: 240px; width: calc(100% - 240px); }
}

@media (max-width: 768px) {
    body { overflow-y: auto !important; }
    .mobile-menu-toggle { display: inline-flex; }
    aside, .sidebar, [class*="sidebar"] { left: -260px !important; transition: all 0.3s ease; }
    aside.active, .sidebar.active, [class*="sidebar"].active { left: 0 !important; }
    .content-wrapper { margin-left: 0 !important; width: 100% !important; }
    .top-navbar { padding: 0 15px; }
    .search-container { width: 140px; }
    .page-container { padding: 10px; }
    .form-banner { padding: 12px 15px; flex-direction: column; gap: 10px; align-items: flex-start; }
    .banner-actions { width: 100%; justify-content: flex-start; flex-wrap: wrap; }
    .filter-box { padding: 15px; gap: 12px; flex-direction: column; align-items: fill; }
    .filter-group { width: 100%; flex-direction: column; align-items: flex-start; gap: 5px; }
    .filter-box select { width: 100%; }
    
    .table-responsive { display: none; }
    .mobile-cards-container { display: flex; }
}

/* CSS rules specifically configuration for standard print layout and PDF saves */
@media print {
    aside, .sidebar, [class*="sidebar"], .top-navbar, .filter-box, .banner-actions, .sidebar-overlay, .mobile-menu-toggle {
        display: none !important;
    }
    .content-wrapper {
        margin-left: 0 !important;
        width: 100% !important;
    }
    body, .main-layout, .content-wrapper, .page-container, .form-card {
        background: #FFFFFF !important;
        box-shadow: none !important;
        padding: 0 !important;
        margin: 0 !important;
    }
    .table-responsive {
        display: block !important;
    }
    .mobile-cards-container {
        display: none !important;
    }
    table th, table td {
        border: 1px solid #CBD5E1 !important;
        padding: 8px 12px !important;
    }
    .ledger-link {
        color: #000000 !important;
        text-decoration: none !important;
    }
    .ledger-link i {
        display: none !important;
    }
}
</style>
</head>
<body>

<div class="sidebar-overlay" id="sidebarOverlay" onclick="toggleMobileSidebar()"></div>

<div class="main-layout">
    
    <?php 
    $sidebar_path = "/home/tameeralmadina/public_html/TAM/sidebar";
    if (file_exists($sidebar_path)) {
        include $sidebar_path;
    } elseif (file_exists($sidebar_path . ".php")) {
        include $sidebar_path . ".php";
    }
    ?>

    <div class="content-wrapper">
        
        <div class="top-navbar">
            <div class="navbar-left-flex">
                <div class="mobile-menu-toggle" onclick="toggleMobileSidebar()">
                    <i class="fa-solid fa-bars"></i>
                </div>
                <div class="search-container">
                    <i class="fa-solid fa-magnifying-glass"></i>
                    <input type="text" placeholder="Search operational ledger logs...">
                </div>
            </div>
            
            <div class="user-profile">
                <div class="profile-info">
                    <i class="fa-solid fa-circle-user profile-icon"></i>
                    <div class="profile-text">
                        <h4>Admin</h4>
                        <p>Administrator</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="page-container">
            <div class="form-card" id="printableLedgerArea">
                
                <div class="form-banner">
                    <div class="banner-left">
                        <div class="banner-icon">
                            <i class="fa-solid fa-chart-line"></i>
                        </div>
                        <div class="banner-text">
                            <h2><?= ucfirst($reference_type); ?> Statement Ledger</h2>
                            <p>Account Holder: <strong><?= htmlspecialchars($ref_name); ?></strong> (ID: #<?= $reference_id ?>)</p>
                        </div>
                    </div>
                    
                    <div class="banner-actions">
                        <button onclick="window.print()" class="btn-action btn-print" title="Print Ledger">
                            <i class="fa-solid fa-print"></i> Print
                        </button>
                        <button onclick="generateLedgerPDF()" class="btn-action btn-pdf" title="Download PDF Ledger">
                            <i class="fa-solid fa-file-pdf"></i> PDF
                        </button>
                        <button onclick="shareOnWhatsApp()" class="btn-action btn-whatsapp" title="Share via WhatsApp">
                            <i class="fa-brands fa-whatsapp"></i> Share
                        </button>
                    </div>
                </div>

                <form method="GET" class="filter-box">
                    <div class="filter-group">
                        <label>Account Category</label>
                        <select name="type" onchange="this.form.submit()">
                            <option value="customer" <?php if($reference_type=='customer') echo 'selected'; ?>>Customer Ledger</option>
                            <option value="supplier" <?php if($reference_type=='supplier') echo 'selected'; ?>>Supplier Ledger</option>
                        </select>
                    </div>

                    <div class="filter-group">
                        <label>Select Entity Party</label>
                        <select name="id" onchange="this.form.submit()">
                            <?php
                            $list = $conn->query("SELECT id, name FROM $ref_table ORDER BY name ASC");
                            while ($r = $list->fetch_assoc()) {
                                $sel = ($r['id'] == $reference_id) ? 'selected' : '';
                                echo "<option value='{$r['id']}' $sel>" . htmlspecialchars($r['name']) . "</option>";
                            }
                            ?>
                        </select>
                    </div>
                </form>

                <!-- Desktop Table Grid Layout -->
                <div class="table-responsive">
                    <table>
                        <thead>
                            <tr>
                                <th style="width: 15%;">Transaction Date</th>
                                <th style="width: 37%;">Description / Reference Voucher</th>
                                <th style="width: 16%;">Debit (Dr.)</th>
                                <th style="width: 16%;">Credit (Cr.)</th>
                                <th style="width: 16%;">Running Balance</th>
                            </tr>
                        </thead>
                        <tbody>

                        <?php
                        if($opening_balance > 0): ?>
                            <tr>
                                <td><span style="color: #A0AEC0;">—</span></td>
                                <td><strong><i class="fa-solid fa-circle-play" style="color:#A0AEC0; margin-right:5px;"></i> Opening Balance</strong></td>
                                <td class="<?= ($reference_type === 'customer' ? 'debit' : 'credit') ?>">OMR <?= number_format($opening_balance, 3) ?></td>
                                <td><span style="color: #CBD5E1;">—</span></td>
                                <td class="balance">OMR <?= number_format($running_balance, 3) ?></td>
                            </tr>
                        <?php endif; ?>

                        <?php if(count($data) > 0): ?>
                            <?php foreach($data as $row):
                                // Database 'DEBIT' / 'CREDIT' case handler integration
                                $debit = (strcasecmp($row['type'], 'DEBIT') === 0) ? (float)$row['amount'] : 0;
                                $credit = (strcasecmp($row['type'], 'CREDIT') === 0) ? (float)$row['amount'] : 0;

                                if ($reference_type === 'customer') {
                                    $running_balance = $running_balance + $debit - $credit;
                                } else {
                                    $running_balance = $running_balance + $credit - $debit;
                                }

                                $formatted_date = date('d M Y', strtotime($row['date']));
                                $desc_raw = trim($row['description']);
                                $desc_display = "";

                                // Check if description is a JSON string or Empty
                                $is_json = false;
                                if (!empty($desc_raw)) {
                                    json_decode($desc_raw);
                                    if (json_last_error() === JSON_ERROR_NONE) {
                                        $is_json = true;
                                    }
                                }

                                if (empty($desc_raw) || $is_json) {
                                    if ($reference_type === 'customer') {
                                        if (strcasecmp($row['type'], 'DEBIT') === 0) {
                                            $invoice_url = "invoice_view.php?id=" . $row['id'];
                                            $desc_display = "<a href='{$invoice_url}' class='ledger-link'><i class='fa-solid fa-arrow-up-right-from-square'></i> View Sales Invoice #INV-00{$row['id']}</a>";
                                        } else {
                                            $desc_display = "Payment Received";
                                        }
                                    } else {
                                        if (strcasecmp($row['type'], 'CREDIT') === 0) {
                                            $purchase_url = "purchase_view.php?id=" . $row['voucher_id'];
                                            $desc_display = "<a href='{$purchase_url}' class='ledger-link'><i class='fa-solid fa-arrow-up-right-from-square'></i> View Purchase Invoice #PCH-00{$row['voucher_id']}</a>";
                                        } else {
                                            $desc_display = "Payment Paid to Supplier";
                                        }
                                    }
                                } else {
                                    $desc_display = htmlspecialchars($desc_raw);
                                }
                            ?>
                                <tr>
                                    <td style="color: #64748B;"><i class="fa-regular fa-calendar-days" style="margin-right: 6px;"></i> <?= $formatted_date ?></td>
                                    <td><?= $desc_display ?></td>
                                    <td class="debit"><?= ($debit > 0 ? 'OMR ' . number_format($debit, 3) : '—') ?></td>
                                    <td class="credit"><?= ($credit > 0 ? 'OMR ' . number_format($credit, 3) : '—') ?></td>
                                    <td class="balance">OMR <?= number_format($running_balance, 3) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php elseif($opening_balance <= 0): ?>
                            <tr>
                                <td colspan="5" class="no-data">
                                    <i class="fa-solid fa-receipt"></i> No transactional logs registered for this profile.
                                </td>
                            </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Mobile Fluid Cards View Architecture -->
                <div class="mobile-cards-container">
                    <?php 
                    // Reset pointer for mobile data layout iteration
                    $running_balance = (float)$opening_balance; 
                    if($opening_balance > 0): 
                    ?>
                        <div class="mobile-card" style="border-left: 4px solid #0d6efd;">
                            <div class="card-header-flex">
                                <div class="card-title-area">
                                    <h3>Opening Balance</h3>
                                    <span>Initial balance initialization parameters</span>
                                </div>
                            </div>
                            <div class="card-body-details">
                                <div class="detail-row">
                                    <span class="label">Amount Type:</span>
                                    <span class="value <?= ($reference_type === 'customer' ? 'debit' : 'credit') ?>">OMR <?= number_format($opening_balance, 3) ?></span>
                                </div>
                                <div class="detail-row" style="margin-top: 5px; padding-top: 5px; border-top: 1px dashed #F1F5F9;">
                                    <span class="label">Balance:</span>
                                    <span class="value balance">OMR <?= number_format($running_balance, 3) ?></span>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if(count($data) > 0): ?>
                        <?php foreach($data as $row):
                            $debit = (strcasecmp($row['type'], 'DEBIT') === 0) ? (float)$row['amount'] : 0;
                            $credit = (strcasecmp($row['type'], 'CREDIT') === 0) ? (float)$row['amount'] : 0;

                            if ($reference_type === 'customer') {
                                $running_balance = $running_balance + $debit - $credit;
                            } else {
                                $running_balance = $running_balance + $credit - $debit;
                            }

                            $formatted_date = date('d M Y', strtotime($row['date']));
                            $desc_raw = trim($row['description']);
                            $desc_display = "";

                            // Check if description is a JSON string or Empty for Mobile view
                            $is_json = false;
                            if (!empty($desc_raw)) {
                                json_decode($desc_raw);
                                if (json_last_error() === JSON_ERROR_NONE) {
                                    $is_json = true;
                                }
                            }

                            if (empty($desc_raw) || $is_json) {
                                if ($reference_type === 'customer') {
                                    if (strcasecmp($row['type'], 'DEBIT') === 0) {
                                        $invoice_url = "invoice_view.php?id=" . $row['id'];
                                        $desc_display = "<a href='{$invoice_url}' class='ledger-link'><i class='fa-solid fa-arrow-up-right-from-square'></i> View Invoice #INV-00{$row['id']}</a>";
                                    } else {
                                        $desc_display = "Payment Received";
                                    }
                                } else {
                                    if (strcasecmp($row['type'], 'CREDIT') === 0) {
                                        $purchase_url = "purchase_view.php?id=" . $row['voucher_id'];
                                        $desc_display = "<a href='{$purchase_url}' class='ledger-link'><i class='fa-solid fa-arrow-up-right-from-square'></i> View Purchase #PCH-00{$row['voucher_id']}</a>";
                                    } else {
                                        $desc_display = "Payment Paid to Supplier";
                                    }
                                }
                            } else {
                                $desc_display = htmlspecialchars($desc_raw);
                            }
                        ?>
                            <div class="mobile-card">
                                <div class="card-header-flex">
                                    <div class="card-title-area">
                                        <h3><?= $desc_display ?></h3>
                                        <span><i class="fa-regular fa-calendar-days"></i> <?= $formatted_date ?></span>
                                    </div>
                                </div>
                                <div class="card-body-details">
                                    <?php if($debit > 0): ?>
                                        <div class="detail-row">
                                            <span class="label">Debit (Dr):</span>
                                            <span class="value debit">OMR <?= number_format($debit, 3) ?></span>
                                        </div>
                                    <?php endif; ?>
                                    <?php if($credit > 0): ?>
                                        <div class="detail-row">
                                            <span class="label">Credit (Cr):</span>
                                            <span class="value credit">OMR <?= number_format($credit, 3) ?></span>
                                        </div>
                                    <?php endif; ?>
                                    <div class="detail-row" style="margin-top: 5px; padding-top: 5px; border-top: 1px dashed #F1F5F9;">
                                        <span class="label">Running Balance:</span>
                                        <span class="value balance">OMR <?= number_format($running_balance, 3) ?></span>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php elseif($opening_balance <= 0): ?>
                        <div class="no-data" style="background:#FFF; border-radius:8px; border:1px solid #E2E8F0;">
                            <i class="fa-solid fa-receipt"></i> No transactional logs registered for this profile.
                        </div>
                    <?php endif; ?>
                </div>

            </div>
        </div>
    </div>
</div>

<script>
function toggleMobileSidebar() {
    const sidebarElements = document.querySelectorAll('aside, .sidebar, [class*="sidebar"]');
    const overlay = document.getElementById('sidebarOverlay');
    
    sidebarElements.forEach(sidebar => {
        sidebar.classList.toggle('active');
    });
    
    if(sidebarElements[0] && sidebarElements[0].classList.contains('active')) {
        overlay.style.display = 'block';
    } else {
        overlay.style.display = 'none';
    }
}

// Client side HTML element to PDF rendering sequence
function generateLedgerPDF() {
    const element = document.getElementById('printableLedgerArea');
    const entityName = "<?= htmlspecialchars($ref_name); ?>";
    const ledgerType = "<?= ucfirst($reference_type); ?>";
    
    // Configurations for high quality PDF output
    const opt = {
        margin:       [10, 10, 10, 10],
        filename:     `${ledgerType}_Ledger_${entityName.replace(/\s+/g, '_')}.pdf`,
        image:        { type: 'jpeg', quality: 0.98 },
        html2canvas:  { scale: 2, useCORS: true },
        jsPDF:        { unit: 'mm', format: 'a4', orientation: 'portrait' }
    };

    // Temporarily hide actions & filters during execution capture
    const actions = document.querySelector('.banner-actions');
    const filters = document.querySelector('.filter-box');
    if(actions) actions.style.visibility = 'hidden';
    if(filters) filters.style.visibility = 'hidden';

    html2pdf().set(opt).from(element).save().then(() => {
        if(actions) actions.style.visibility = 'visible';
        if(filters) filters.style.visibility = 'visible';
    }).catch(err => {
        console.error("PDF generation failed:", err);
        if(actions) actions.style.visibility = 'visible';
        if(filters) filters.style.visibility = 'visible';
    });
}

// WhatsApp redirect parsing data strings
function shareOnWhatsApp() {
    const entityName = "<?= htmlspecialchars($ref_name); ?>";
    const ledgerType = "<?= ucfirst($reference_type); ?>";
    const currentUrl = window.location.href;
    
    // Custom formatted text structure for instant preview
    const message = `*Tameer Al Madina - Account Statement Update*\n\n` +
                    `*Type:* ${ledgerType} Ledger\n` +
                    `*Account Holder:* ${entityName}\n\n` +
                    `Please check the live interactive ledger via this document interface link:\n` + 
                    `${currentUrl}`;
                    
    const whatsappUrl = `https://api.whatsapp.com/send?text=${encodeURIComponent(message)}`;
    window.open(whatsappUrl, '_blank');
}
</script>
</body>
</html>