<?php
// Session & Config
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
date_default_timezone_set('Asia/Vientiane');

require_once '../../include/con_data.php';

// Check Auth
if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit;
}

$shop_id = $_SESSION['shop_id'] ?? null;

// ==========================================
// AJAX HANDLERS
// ==========================================
if (isset($_GET['ajax']) && $_GET['ajax'] === 'receipts') {
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $date_from = $_GET['date_from'] ?? '';
    $date_to = $_GET['date_to'] ?? '';
    $users_filter = isset($_GET['users']) ? trim($_GET['users']) : '';

    $where = "o.shop_id = ? AND o.order_status != 'cancelled'";
    $params = [$shop_id];
    $types = "i";

    if ($users_filter) {
        $user_ids = array_filter(array_map('trim', explode(',', $users_filter)));
        if (!empty($user_ids)) {
            $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
            $where .= " AND o.created_by IN ($placeholders)";
            foreach ($user_ids as $uid) {
                array_push($params, $uid);
                $types .= "s";
            }
        }
    }

    if ($search) {
        $where .= " AND (o.OR_id LIKE ? OR c.name LIKE ? OR c.phone LIKE ? OR o.bill_number LIKE ?)";
        $s = "%$search%";
        array_push($params, $s, $s, $s, $s);
        $types .= "ssss";
    } elseif ($date_from && $date_to) {
        $where .= " AND DATE(o.created_at) BETWEEN ? AND ?";
        array_push($params, $date_from, $date_to);
        $types .= "ss";
    }

    $sql = "SELECT o.*, c.name as customer_name, c.phone as customer_phone,
                   sc.company_name, sb.branch_name,
                   cur.currencys_symbol
            FROM orders o
            LEFT JOIN customers c ON o.customer_id = c.CU_id
            LEFT JOIN shipping_companies sc ON o.shipping_company_id = sc.SC_id
            LEFT JOIN shipping_branches sb ON o.shipping_branch_id = sb.SB_id
            LEFT JOIN currencys cur ON o.currencys_id = cur.currencys_id AND cur.shop_id = o.shop_id
            WHERE $where
            ORDER BY o.created_at ASC
            LIMIT ? OFFSET ?";

    $page = max(1, intval($_GET['page'] ?? 1));
    $limit = 50;
    $offset = ($page - 1) * $limit;

    array_push($params, $limit, $offset);
    $types .= "ii";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    // Get shop info for the receipts
    $shop_stmt = $conn->prepare("SELECT * FROM shops WHERE shop_id = ?");
    $shop_stmt->bind_param("i", $shop_id);
    $shop_stmt->execute();
    $shop_result = $shop_stmt->get_result();
    $shop = $shop_result->fetch_assoc();
    $shop_stmt->close();

    $shop_name = $shop['shop_name'] ?? 'Muanjai Shop';
    $shop_phone = $shop['phone'] ?? '-';

    if ($result->num_rows > 0) {
        while ($order = $result->fetch_assoc()) {
            $order_type = $order['order_type'];
            $currency_symbol = $order['currencys_symbol'] ?? '₭';

            // Get Items
            $items_sql = "SELECT * FROM order_items WHERE order_id = ?";
            $istmt = $conn->prepare($items_sql);
            $istmt->bind_param("i", $order['id']);
            $istmt->execute();
            $iresult = $istmt->get_result();
            $items = [];
            while ($row = $iresult->fetch_assoc()) {
                $items[] = $row;
            }
            $istmt->close();

            // Extract COD info
            $cod_info = '-';
            if (!empty($order['notes'])) {
                if (strpos($order['notes'], 'ປາຍທາງ') !== false) {
                    $cod_info = 'ປາຍທາງ';
                } elseif (strpos($order['notes'], 'ຕົ້ນທາງ') !== false || strpos($order['notes'], 'ຫັກ COD') !== false) {
                    $cod_info = 'ຕົ້ນທາງ';
                }
            }

            // QR Code URl
            $protocol = 'https';
            $fixed_domain = 'epgroups.com';
            $base_dir = rtrim(dirname($_SERVER['REQUEST_URI']), '/');
            $view_order_url = $protocol . "://" . $fixed_domain . $base_dir . "/view_order.php?id=" . $order['OR_id'];
            $qr_api_url = "https://api.qrserver.com/v1/create-qr-code/?size=110x110&margin=0&data=" . urlencode($view_order_url);

            echo '<div class="invoice-thumbnail-wrapper" onclick="toggleCheckbox(this, event)">';
            echo '<div class="invoice-checkbox-container" onclick="event.stopPropagation();">';
            echo '<input type="checkbox" class="invoice-checkbox" value="' . $order['OR_id'] . '" onclick="event.stopPropagation();">';
            echo '</div>';
            echo '<div class="invoice-thumbnail-content">';

            if ($order_type === 'online') {
                ?>
                <!-- ========== ONLINE RECEIPT ========== -->
                <div class="receipt">
                    <!-- HEADER -->
                    <div class="receipt-header">
                        <div class="header-left">
                            <div class="header-logo">
                                <img src="../../img/logo_icon/logo.png" alt="MUANJAI">
                            </div>
                            <div class="header-brand">
                                <div class="slogan">ເພາະຄວາມສຸກຂອງທ່ານ</div>
                                <div class="slogan">ຄືຄວາມພາກພູມໃຈຂອງເຮົາ</div>
                            </div>
                        </div>
                        <div class="header-right">
                            <div class="social-grid">
                                <div class="social-item">
                                    <img src="../../img/logo_icon/facebook.png" alt="fb"> MUANJAI
                                </div>
                                <div class="social-item">
                                    <img src="../../img/logo_icon/whatapp.png" alt="wa"> 020
                                    <?= htmlspecialchars($shop_phone) ?>
                                </div>
                                <div class="social-item">
                                    <img src="../../img/logo_icon/tiktok.png" alt="tt"> MUANJAI
                                </div>
                                <div class="social-item">
                                    <img src="../../img/logo_icon/ins.png" alt="ig"> Muanjai_Beauty
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- INFO SECTION -->
                    <div class="receipt-info">
                        <div class="info-row first-row">
                            <div class="info-cell" style="text-align: left;">
                                <span class="info-label">ເລກບິນ:</span>
                                <span class="info-value">
                                    <?= htmlspecialchars($order['OR_id']) ?>
                                </span>
                            </div>
                            <div class="info-cell" style="text-align: right;">
                                <span class="info-label">ວ/ດ/ປ:</span>
                                <span class="info-value">
                                    <?= date('d/m/Y', strtotime($order['created_at'])) ?>
                                </span>
                            </div>
                        </div>

                        <div class="info-row">
                            <div class="info-cell">
                                <span class="info-label">ຜູ້ຝາກ:</span>
                                <span class="info-value">MUANJAI</span>
                            </div>
                            <div class="info-cell">
                                <span class="info-label">ເບີຜູ້ຝາກ:</span>
                                <span class="info-value">
                                    <?= htmlspecialchars($shop_phone) ?>
                                </span>
                            </div>
                        </div>

                        <div class="info-row">
                            <div class="info-cell">
                                <span class="info-label">ຜູ້ຮັບ:</span>
                                <span class="info-value">
                                    <?= htmlspecialchars($order['customer_name'] ?? '-') ?>
                                </span>
                            </div>
                            <div class="info-cell">
                                <span class="info-label">ເບີຜູ້ຮັບ:</span>
                                <span class="info-value">
                                    <?= htmlspecialchars($order['customer_phone'] ?? '-') ?>
                                </span>
                            </div>
                        </div>

                        <div class="info-row">
                            <div class="info-cell">
                                <span class="info-label">ຂົນສົ່ງ:</span>
                                <span class="info-value bold">
                                    <?= htmlspecialchars($order['company_name'] ?? '-') ?>
                                </span>
                            </div>
                            <div class="info-cell">
                                <span class="info-label">ຄ່າຝາກ:</span>
                                <span class="info-value bold">
                                    <?= $cod_info ?>
                                </span>
                            </div>
                        </div>

                        <div class="info-row last-row">
                            <div class="info-cell full">
                                <span class="info-label">ສາຂາຝາກ:</span>
                                <span class="info-value">
                                    <?= htmlspecialchars($order['branch_name'] ?? '-') ?>
                                </span>
                            </div>
                        </div>
                    </div>

                    <!-- FOOTER -->
                    <div class="receipt-footer">
                        <div class="footer-left">
                            <div class="warning-item">
                                <div class="warning-icon">
                                    <img src="../../img/logo_icon/video.png" alt="video">
                                </div>
                                <div class="warning-text">
                                    ບັນທຶກວິດິໂອກ່ອນເປີດກ່ອງທຸກຄັ້ງ
                                </div>
                            </div>
                            <div class="warning-item">
                                <div class="warning-icon">
                                    <img src="../../img/logo_icon/grass.png" alt="fragile">
                                </div>
                                <div class="warning-text">
                                    ຫ້າມໂຍນ ລະທວັງແຕກ<br>
                                    <span class="fragile-en">( FRAGILE )</span>
                                </div>
                            </div>
                        </div>
                        <div class="footer-right">
                            <div class="qr-placeholder">
                                <img src="<?= $qr_api_url ?>" alt="QR Code" loading="lazy">
                            </div>
                        </div>
                    </div>
                </div>
                <?php
            } else {
                // ========== POS RECEIPT ========== 
                ?>
                <div class="receipt-pos">
                    <div class="pos-header">
                        <img src="../../img/logo_icon/logo.png" alt="MUANJAI">
                        <div class="pos-shop-name">MUANJAI</div>
                        <div class="pos-phone">Tel:
                            <?= htmlspecialchars($shop_phone) ?>
                        </div>
                    </div>

                    <div class="pos-meta">
                        <span><strong>ເລກບິນ:</strong>
                            <?= $order['OR_id'] ?>
                        </span>
                        <span>
                            <?= date('d/m/Y H:i', strtotime($order['created_at'])) ?>
                        </span>
                    </div>

                    <table class="pos-table">
                        <thead>
                            <tr>
                                <th>ລາຍການ</th>
                                <th style="text-align:center; width:15%;">ຈນ</th>
                                <th style="text-align:right; width:25%;">ລວມ</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($items as $item): ?>
                                <tr>
                                    <td>
                                        <?= htmlspecialchars($item['product_name']) ?>
                                    </td>
                                    <td style="text-align:center;">
                                        <?= $item['quantity'] ?>
                                    </td>
                                    <td style="text-align:right;">
                                        <?= number_format($item['total']) ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                    <div class="pos-totals">
                        <div class="pos-total-row">
                            <span>ລວມຍ່ອຍ:</span>
                            <span>
                                <?= number_format($order['subtotal']) ?>
                                <?= $currency_symbol ?>
                            </span>
                        </div>
                        <?php if ($order['discount_amount'] > 0): ?>
                            <div class="pos-total-row">
                                <span>ສ່ວນຫຼຸດ:</span>
                                <span>-
                                    <?= number_format($order['discount_amount']) ?>
                                    <?= $currency_symbol ?>
                                </span>
                            </div>
                        <?php endif; ?>
                        <?php if ($order['tax_amount'] > 0): ?>
                            <div class="pos-total-row">
                                <span>VAT (10%):</span>
                                <span>
                                    <?= number_format($order['tax_amount']) ?>
                                    <?= $currency_symbol ?>
                                </span>
                            </div>
                        <?php endif; ?>
                        <div class="pos-total-row grand">
                            <span>ສຸດທິ:</span>
                            <span>
                                <?= number_format($order['total_amount']) ?>
                                <?= $currency_symbol ?>
                            </span>
                        </div>
                    </div>

                    <?php if ($order['cash_received'] > 0): ?>
                        <div class="pos-cash-info">
                            <div class="pos-cash-row">
                                <span>ຮັບເງິນ:</span>
                                <span>
                                    <?= number_format($order['cash_received']) ?>
                                    <?= $currency_symbol ?>
                                </span>
                            </div>
                            <div class="pos-cash-row">
                                <span>ເງິນທອນ:</span>
                                <span>
                                    <?= number_format($order['cash_change']) ?>
                                    <?= $currency_symbol ?>
                                </span>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="pos-footer">
                        ຂອບໃຈທີ່ໃຊ້ບໍລິການ
                    </div>
                </div>
                <?php
            }
            echo '</div>'; // close invoice-thumbnail-content
            echo '<div class="print-overlay" onclick="event.stopPropagation(); printSpecificOrder(\'' . $order['OR_id'] . '\')"><i class="fas fa-print"></i> ພິມ</div>';
            echo '</div>'; // close invoice-thumbnail-wrapper
        }
    } else {
        echo '<div class="empty-state" style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #888;">ບໍ່ພົບຂໍ້ມູນ</div>';
    }
    exit;
}

// --- Pagination Handler ---
if (isset($_GET['ajax']) && $_GET['ajax'] === 'pagination') {
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $date_from = $_GET['date_from'] ?? '';
    $date_to = $_GET['date_to'] ?? '';
    $users_filter = isset($_GET['users']) ? trim($_GET['users']) : '';
    $page = max(1, intval($_GET['page'] ?? 1));
    $limit = 50;

    $where = "o.shop_id = ? AND o.order_status != 'cancelled'";
    $params = [$shop_id];
    $types = "i";

    if ($users_filter) {
        $user_ids = array_filter(array_map('trim', explode(',', $users_filter)));
        if (!empty($user_ids)) {
            $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
            $where .= " AND o.created_by IN ($placeholders)";
            foreach ($user_ids as $uid) {
                array_push($params, $uid);
                $types .= "s";
            }
        }
    }

    if ($search) {
        $where .= " AND (o.OR_id LIKE ? OR c.name LIKE ? OR c.phone LIKE ? OR o.bill_number LIKE ?)";
        $s = "%$search%";
        array_push($params, $s, $s, $s, $s);
        $types .= "ssss";
    } elseif ($date_from && $date_to) {
        $where .= " AND DATE(o.created_at) BETWEEN ? AND ?";
        array_push($params, $date_from, $date_to);
        $types .= "ss";
    }

    $sql = "SELECT COUNT(*) as total FROM orders o 
            LEFT JOIN customers c ON o.customer_id = c.CU_id 
            WHERE $where";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $total_rows = $stmt->get_result()->fetch_assoc()['total'];
    $total_pages = ceil($total_rows / $limit);

    echo '<div class="pagination-info">ທັງໝົດ ' . number_format($total_rows) . ' ລາຍການ</div>';
    echo '<div class="pagination-btns">';
    if ($total_pages > 1) {
        if ($page > 1)
            echo '<button onclick="loadReceiptsPage(' . ($page - 1) . ')"><i class="fas fa-angle-left"></i></button>';

        $start = max(1, $page - 2);
        $end = min($total_pages, $page + 2);
        for ($i = $start; $i <= $end; $i++) {
            $active = ($i == $page) ? 'active' : '';
            echo '<button class="' . $active . '" onclick="loadReceiptsPage(' . $i . ')">' . $i . '</button>';
        }

        if ($page < $total_pages)
            echo '<button onclick="loadReceiptsPage(' . ($page + 1) . ')"><i class="fas fa-angle-right"></i></button>';
    }
    echo '</div>';
    exit;
}

$page_title = 'ໃບບິນທັງໝົດ - Invoices';
require_once '../includes/header.php';

// Load users for the multi-select filter
$users_list = [];
try {
    $userStmt = $pdo->prepare("SELECT user_id, name FROM users WHERE shop_id = :shop_id ORDER BY name");
    $userStmt->execute([':shop_id' => $shop_id]);
    $users_list = $userStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // silently handle
}
?>

<style>
    /* Prevent SweetAlert scrollbar jitter */
    html {
        scrollbar-gutter: stable;
    }

    /* Page styles */
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        flex-wrap: wrap;
        gap: 16px;
    }

    .page-header h1 {
        font-size: 24px;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 12px;
        margin: 0;
    }

    .filter-card {
        background: var(--card-bg, #fff);
        border: 1px solid var(--border-color, #eaeaea);
        border-radius: 16px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.02);
    }

    /* Multi-select filter styles */
    .user-filter-wrapper {
        position: relative;
        min-width: 200px;
    }

    .user-filter-btn {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 16px;
        background: var(--bg-secondary);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        color: var(--text-primary);
        font-size: 16px;
        cursor: pointer;
        width: 100%;
        text-align: left;
    }

    .user-filter-btn:hover {
        border-color: var(--accent);
    }

    .user-filter-dropdown {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        margin-top: 4px;
        background: var(--bg-secondary, #fff);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        z-index: 100;
        display: none;
        max-height: 300px;
        overflow-y: auto;
        padding: 8px 0;
    }

    .user-filter-dropdown.show {
        display: block;
    }

    .user-filter-item {
        padding: 8px 16px;
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
    }

    .user-filter-item:hover {
        background: rgba(var(--accent-rgb), 0.05);
    }

    .user-filter-item input[type="checkbox"] {
        cursor: pointer;
        width: 16px;
        height: 16px;
    }

    .user-filter-count {
        background: var(--accent);
        color: white;
        font-size: 12px;
        padding: 2px 6px;
        border-radius: 10px;
        margin-left: 8px;
        display: none;
    }

    .filter-row {
        display: flex;
        gap: 16px;
        flex-wrap: wrap;
        align-items: center;
    }

    .search-box {
        display: flex;
        align-items: center;
        gap: 8px;
        background: var(--bg-secondary);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        padding: 12px 16px;
        flex: 1;
        min-width: 250px;
    }

    .search-box input {
        border: none;
        background: transparent;
        outline: none;
        color: var(--text-primary, #333);
        width: 100%;
        font-size: 16px;
    }

    .date-input {
        padding: 12px 16px;
        border: 1px solid var(--border-color);
        border-radius: 10px;
        background: var(--bg-secondary);
        color: var(--text-primary);
        font-size: 16px;
        color-scheme: dark;
    }

    [data-theme="light"] .date-input {
        color-scheme: light;
    }

    .btn-pro {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 12px 20px;
        border-radius: 10px;
        border: none;
        font-weight: 600;
        cursor: pointer;
        transition: all .3s;
        font-size: 16px;
    }

    .btn-pro.primary {
        background: linear-gradient(135deg, var(--accent, #4a90e2), var(--accent-soft, #357abd));
        color: #fff;
        box-shadow: 0 4px 15px rgba(74, 144, 217, .3);
    }

    .btn-pro.primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(74, 144, 217, .4);
    }

    .btn-pro.danger {
        background: #dc3545;
        color: white;
    }

    .btn-pro.danger:hover {
        background: #c82333;
    }

    .btn-reset {
        background: #6c757d;
        color: #fff;
        padding: 12px 20px;
        border-radius: 10px;
        border: none;
        font-weight: 500;
        cursor: pointer;
        font-size: 14px;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    /* Grid layout for invoices */
    .invoices-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
        gap: 24px;
        margin-top: 20px;
    }

    /* Pagination */
    .pagination-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        border-top: 1px solid var(--border-color);
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 20px;
    }

    .pagination-info {
        font-size: 14px;
        color: var(--text-secondary);
    }

    .pagination-btns {
        display: flex;
        gap: 4px;
    }

    .pagination-btns button {
        min-width: 36px;
        height: 36px;
        border: 1px solid var(--border-color);
        background: var(--card-bg);
        color: var(--text-primary);
        border-radius: 8px;
        cursor: pointer;
        font-size: 13px;
        transition: all .2s;
        font-family: inherit;
    }

    .pagination-btns button:hover {
        border-color: var(--accent);
        color: var(--accent);
    }

    .pagination-btns button.active {
        background: var(--accent);
        color: #fff;
        border-color: var(--accent);
    }

    .pagination-btns button:disabled {
        opacity: .4;
        cursor: not-allowed;
    }

    /* Thumbnail Wrapper */
    .invoice-thumbnail-wrapper {
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.06);
        cursor: pointer;
        transition: all 0.3s ease;
        overflow: hidden;
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        /* Define fixed container sizes to allow scaling inside */
        height: 280px;
    }

    .invoice-checkbox-container {
        position: absolute;
        top: 10px;
        left: 10px;
        z-index: 10;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 6px;
        padding: 5px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        display: none;
        /* hidden by default */
        align-items: center;
        justify-content: center;
    }

    .invoice-checkbox-container.show {
        display: flex;
    }

    .invoice-checkbox {
        width: 18px;
        height: 18px;
        cursor: pointer;
    }

    /* Bulk Actions */
    .bulk-actions {
        display: none;
        align-items: center;
        gap: 10px;
        margin-left: 10px;
    }

    .bulk-actions.show {
        display: flex;
    }

    .invoice-thumbnail-wrapper:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
        border-color: var(--accent, #4a90e2);
    }

    .invoice-thumbnail-wrapper:hover .print-overlay {
        opacity: 1;
    }

    .print-overlay {
        position: absolute;
        bottom: 10px;
        right: 10px;
        background: var(--accent, #4a90e2);
        color: white;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 13px;
        font-weight: 600;
        opacity: 0;
        transition: opacity 0.2s;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        z-index: 10;
    }

    /* Container for scaling down the actual receipt without shrinking its internal properties */
    .invoice-thumbnail-content {
        transform-origin: top center;
        transform: scale(0.5);
        /* Make it 50% size for the thumbnail */
        width: 100mm;
        /* Force native size */
        display: flex;
        justify-content: center;
        pointer-events: none;
        /* Let clicks pass to wrapper */
        margin-top: 20px;
    }

    /* ========== ORIGINAL RECEIPT STYLES FROM print_invoice.php ========== */
    .receipt {
        width: 100mm;
        height: 80mm;
        background: #fff;
        border: 2.5px solid #000;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        color: #000;
        flex-shrink: 0;
    }

    .receipt-header {
        display: flex;
        align-items: stretch;
        border-bottom: 2.5px solid #000;
    }

    .header-left {
        display: flex;
        align-items: center;
        flex: 1;
    }

    .header-logo {
        width: 16mm;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .header-logo img {
        width: 9.401mm;
        height: 8.696mm;
    }

    .header-brand {
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .header-brand .slogan {
        font-size: 9pt;
        font-weight: 600;
        line-height: 1.4;
        color: #000;
    }

    .header-right {
        flex: 1;
        border-left: 2.5px solid #000;
        display: flex;
        padding: 3px 3px 3px 2px;
        flex-direction: column;
        justify-content: center;
    }

    .social-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
    }

    .social-item {
        display: flex;
        align-items: center;
        gap: 1.5mm;
        font-size: 8pt;
        font-weight: 700;
        color: #000;
        white-space: nowrap;
    }

    .social-item img {
        width: 3.5mm;
        height: 3.5mm;
        object-fit: contain;
    }

    .receipt-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        padding: 1mm 0;
    }

    .info-row {
        display: grid;
        grid-template-columns: 1.6fr 1fr;
        padding-left: 8px;
        padding-right: 8px;
        gap: 2mm;
    }

    .info-cell {
        display: block;
    }

    .info-cell.full {
        grid-column: 1 / -1;
    }

    .info-label {
        font-size: 10pt;
        font-weight: 800;
        color: #000;
        white-space: nowrap;
    }

    .info-value {
        font-size: 10pt;
        font-weight: 500;
        color: #000;
    }

    .info-value.bold {
        font-weight: 900;
        font-size: 13pt;
    }

    .info-row.first-row {
        border-bottom: 1.5px solid #000;
        padding-top: 1.5mm;
        padding-bottom: 1.5mm;
    }

    .info-row.last-row {
        padding-bottom: 1.5mm;
    }

    .receipt-footer {
        display: flex;
        border-top: 2.5px solid #000;
        min-height: 20mm;
    }

    .footer-left {
        flex: 1;
        padding: 2mm;
        display: flex;
        flex-direction: column;
        justify-content: center;
        gap: 2mm;
    }

    .warning-item {
        display: flex;
        align-items: center;
        gap: 2.5mm;
    }

    .warning-icon {
        flex-shrink: 0;
    }

    .warning-icon img {
        width: 8mm;
        height: 8mm;
        object-fit: contain;
    }

    .warning-text {
        font-size: 12pt;
        font-weight: 700;
        line-height: 1.3;
        color: #000;
    }

    .warning-text .fragile-en {
        font-weight: 900;
        font-size: 9pt;
        letter-spacing: 1px;
    }

    .footer-right {
        width: 32mm;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 2mm;
    }

    .qr-placeholder {
        width: 28mm;
        height: 28mm;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .qr-placeholder img {
        width: 90px;
        height: 90px;
        object-fit: contain;
    }

    .receipt-pos {
        width: 70mm;
        padding: 3mm;
        background: #fff;
        border: 2px solid #000;
        color: #000;
        flex-shrink: 0;
    }

    .pos-header {
        text-align: center;
        border-bottom: 2px solid #000;
        padding-bottom: 2mm;
        margin-bottom: 2mm;
    }

    .pos-header img {
        width: 10mm;
        margin-bottom: 1mm;
    }

    .pos-header .pos-shop-name {
        font-size: 11pt;
        font-weight: 800;
    }

    .pos-header .pos-phone {
        font-size: 7.5pt;
        color: #333;
    }

    .pos-meta {
        display: flex;
        justify-content: space-between;
        font-size: 7pt;
        border-bottom: 1px solid #000;
        padding-bottom: 2mm;
        margin-bottom: 2mm;
    }

    .pos-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 7.5pt;
        margin-bottom: 2mm;
        color: #000;
    }

    .pos-table th {
        text-align: left;
        border-bottom: 1px solid #000;
        padding: 1mm 0;
        font-weight: 700;
        font-size: 7pt;
    }

    .pos-table td {
        padding: 1mm 0;
        border-bottom: 0.5px solid #ddd;
    }

    .pos-totals {
        border-top: 2px solid #000;
        padding-top: 2mm;
        margin-top: 1mm;
    }

    .pos-total-row {
        display: flex;
        justify-content: space-between;
        font-size: 8pt;
        padding: 0.5mm 0;
    }

    .pos-total-row.grand {
        font-size: 11pt;
        font-weight: 800;
        border-top: 1px solid #000;
        padding-top: 1.5mm;
        margin-top: 1mm;
    }

    .pos-cash-info {
        border-top: 1px dashed #000;
        margin-top: 2mm;
        padding-top: 2mm;
        font-size: 7pt;
    }

    .pos-cash-row {
        display: flex;
        justify-content: space-between;
        padding: 0.3mm 0;
    }

    .pos-footer {
        text-align: center;
        margin-top: 3mm;
        padding-top: 2mm;
        border-top: 1px solid #000;
        font-size: 7.5pt;
        font-weight: 500;
    }

    /* Modal Styles */
    #invoiceModal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.7);
        backdrop-filter: blur(5px);
        z-index: 9999;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
    }

    #invoiceModal.show {
        opacity: 1;
        visibility: visible;
    }

    .modal-invoice-container {
        background: transparent;
        position: relative;
        transform: scale(0.8) translateY(20px);
        transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);

        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: auto;
    }

    /* Ensure modal shows scrollbar nicely if content is too tall */
    .modal-invoice-container::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    .modal-invoice-container::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 4px;
    }

    .modal-invoice-container::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.3);
        border-radius: 4px;
    }

    #invoiceModal.show .modal-invoice-container {
        transform: scale(1) translateY(0);
    }

    /* In the modal, we want the receipt to be normal size and nicely shadowed */
    .modal-invoice-container .receipt,
    .modal-invoice-container .receipt-pos {
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
        border-radius: 2px;
        background: #fff;

        /* Reset any inherited miniaturization */
        flex-shrink: 0;

        /* Scale it up slightly for better readability */
        transform: scale(1.5);

        /* Ensure there's space around the scaled element so it can be scrolled to */
        margin: 50px auto;
    }

    /* Media queries for smaller screens to ensure it fits */
    @media (max-width: 768px) {

        .modal-invoice-container .receipt,
        .modal-invoice-container .receipt-pos {
            transform: scale(0.9);
            margin: 20px auto;
        }
    }

    .close-modal-btn {
        position: absolute;
        top: 10px;
        right: 10px;
        background: #fff;
        color: #333;
        border: none;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        font-size: 20px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
        z-index: 10000;
        transition: all 0.2s;
    }

    .close-modal-btn:hover {
        background: #ff4d4f;
        color: white;
        transform: scale(1.1);
    }

    .print-modal-btn {
        position: absolute;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        padding: 12px 30px;
        background: linear-gradient(135deg, var(--accent, #4a90e2), var(--accent-soft, #357abd));
        color: white;
        border: none;
        border-radius: 30px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
        display: flex;
        align-items: center;
        gap: 10px;
        transition: all 0.2s;
        z-index: 10000;
    }

    .print-modal-btn:hover {
        transform: translateX(-50%) translateY(-3px);
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
    }
</style>

<div class="page-header">
    <h1>
        <div class="icon-box"
            style="background: rgba(var(--accent-rgb, 74, 144, 217), 0.1); color: var(--accent, #4a90e2); padding: 12px; border-radius: 12px;">
            <i class="fas fa-file-invoice"></i>
        </div>
        ໃບບິນທັງໝົດ - Invoices Dashboard
    </h1>

    <div style="display:flex; gap:10px; align-items:center;">
        <button type="button" id="toggle-bulk-select" class="btn-pro secondary" onclick="toggleBulkSelect()">
            <i class="fas fa-check-square"></i> ເລືອກຫຼາຍລາຍການ
        </button>
        <div class="bulk-actions" id="bulk-actions">
            <label style="display:flex; align-items:center; gap:5px; cursor:pointer;" onclick="toggleAllInvoices(this)">
                <input type="checkbox" id="selectAllInvoices" style="width:18px; height:18px; cursor:pointer;">
                <span style="font-weight:600; color:var(--text-primary);">ເລືອກທັງໝົດ</span>
            </label>
            <button class="btn-pro danger" onclick="printSelectedOrAll()"><i class="fas fa-print"></i> ພິມທີ່ເລືອກ /
                ທັງໝົດ</button>
            <button id="cancel-selection" class="btn-pro secondary" onclick="cancelBulkSelect()">
                <i class="fas fa-times"></i> ຍົກເລີກ
            </button>
        </div>
    </div>
</div>

<div class="filter-card">
    <div class="filter-row">
        <div class="search-box">
            <i class="fas fa-search" style="color: var(--text-secondary, #6c757d);"></i>
            <input type="text" id="searchInput" placeholder="ຄົ້ນຫາເລກບິນ, ຊື່, ເບີໂທ..." value="">
        </div>

        <input type="date" id="dateFrom" class="date-input" value="<?= date('Y-m-d') ?>">
        <span style="color: var(--text-secondary, #6c757d);">ຫາ</span>
        <input type="date" id="dateTo" class="date-input" value="<?= date('Y-m-d') ?>">

        <!-- User Filter -->
        <div class="user-filter-wrapper" id="user-filter-wrapper">
            <button class="user-filter-btn" type="button" onclick="toggleUserFilter()">
                <span><i class="fas fa-users" style="margin-right:6px"></i> ພະນັກງານ <span id="user-filter-count"
                        class="user-filter-count">0</span></span>
                <i class="fas fa-chevron-down" style="font-size: 12px; opacity: 0.7;"></i>
            </button>
            <div class="user-filter-dropdown" id="user-filter-dropdown">
                <label class="user-filter-item">
                    <input type="checkbox" id="user-filter-all" onchange="toggleAllUsers(this)" checked>
                    <strong>ທັງໝົດ (Show All)</strong>
                </label>
                <div style="height: 1px; background: var(--border-color); margin: 4px 0;"></div>
                <?php foreach ($users_list as $u): ?>
                    <label class="user-filter-item">
                        <input type="checkbox" class="user-filter-checkbox" value="<?= htmlspecialchars($u['user_id']) ?>"
                            onchange="updateUserFilterCount()">
                        <?= htmlspecialchars($u['name']) ?>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>

        <button class="btn-pro primary" onclick="loadReceipts()"><i class="fas fa-filter"></i> ກັ່ນຕອງ</button>
        <button class="btn-reset" onclick="resetFilters()"><i class="fas fa-sync-alt"></i></button>
    </div>
</div>

<div id="loadingIndicator" style="display:none; text-align:center; padding: 40px;">
    <i class="fas fa-spinner fa-spin fa-3x" style="color: var(--accent, #4a90e2);"></i>
    <p style="margin-top:15px; color: var(--text-secondary, #6c757d);">ກຳລັງໂຫຼດຂໍ້ມູນ...</p>
</div>

<!-- Output Grid -->
<div class="invoices-grid" id="invoicesGrid">
    <!-- Receipts will be loaded here via AJAX -->
</div>

<div id="pagination" class="pagination-wrap"></div>

<!-- Modal for viewing full receipt -->
<div id="invoiceModal" onclick="closeInvoiceModal(event)">
    <button class="close-modal-btn" onclick="closeInvoiceModal(event)"><i class="fas fa-times"></i></button>
    <div class="modal-invoice-container" id="modalInvoiceContent" onclick="event.stopPropagation()">
        <!-- Cloned receipt goes here -->
    </div>
    <button class="print-modal-btn" id="printModalBtn" onclick="event.stopPropagation()"><i class="fas fa-print"></i>
        ພິມໃບບິນນີ້ (Print)</button>
</div>

<!-- Hidden iframe for printing without leaving the page -->
<iframe id="printFrame" name="printFrame" style="display:none;"></iframe>

<script>
    let currentOrderIdToPrint = null;

    document.addEventListener('DOMContentLoaded', () => {
        // Restore dates from localStorage if available
        const savedDateFrom = localStorage.getItem('invoice_date_from');
        const savedDateTo = localStorage.getItem('invoice_date_to');
        if (savedDateFrom) document.getElementById('dateFrom').value = savedDateFrom;
        if (savedDateTo) document.getElementById('dateTo').value = savedDateTo;

        // Load initial receipts
        loadReceipts();

        // Listen for enter key on search input
        document.getElementById('searchInput').addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                loadReceipts();
            }
        });

        // Close user filter dropdown when clicking outside
        document.addEventListener('click', function (event) {
            const wrapper = document.getElementById('user-filter-wrapper');
            const dropdown = document.getElementById('user-filter-dropdown');
            if (wrapper && dropdown && !wrapper.contains(event.target)) {
                dropdown.classList.remove('show');
            }
        });
    });

    function toggleUserFilter() {
        document.getElementById('user-filter-dropdown').classList.toggle('show');
    }

    function toggleAllUsers(source) {
        const checkboxes = document.querySelectorAll('.user-filter-checkbox');
        checkboxes.forEach(cb => {
            cb.checked = source.checked;
        });
        updateUserFilterCount();
    }

    function updateUserFilterCount() {
        const checkboxes = document.querySelectorAll('.user-filter-checkbox');
        const allCheckbox = document.getElementById('user-filter-all');
        const countBadge = document.getElementById('user-filter-count');

        let checkedCount = 0;
        let uncheckedExist = false;

        checkboxes.forEach(cb => {
            if (cb.checked) {
                checkedCount++;
            } else {
                uncheckedExist = true;
            }
        });

        // Update 'All' checkbox state
        if (allCheckbox) {
            allCheckbox.checked = !uncheckedExist;
        }

        // Update badge
        if (checkedCount === 0 || !uncheckedExist) {
            // Either none selected or all selected
            countBadge.style.display = 'none';
        } else {
            countBadge.textContent = checkedCount;
            countBadge.style.display = 'inline-block';
        }

        loadReceipts();
    }

    let currentPage = 1;

    function loadReceiptsPage(page = 1) {
        currentPage = page;
        const search = document.getElementById('searchInput').value;
        const dateFrom = document.getElementById('dateFrom').value;
        const dateTo = document.getElementById('dateTo').value;

        // Save selected dates to localStorage
        localStorage.setItem('invoice_date_from', dateFrom);
        localStorage.setItem('invoice_date_to', dateTo);

        // Get selected users
        const checkboxes = document.querySelectorAll('.user-filter-checkbox:checked');
        const userIds = Array.from(checkboxes).map(cb => cb.value).join(',');

        const grid = document.getElementById('invoicesGrid');
        const pagination = document.getElementById('pagination');
        const loader = document.getElementById('loadingIndicator');

        grid.innerHTML = '';
        if (pagination) pagination.innerHTML = '';
        loader.style.display = 'block';

        const params = new URLSearchParams({
            search: search,
            date_from: dateFrom,
            date_to: dateTo,
            page: page
        });

        // Only append users if not all are selected and some are selected
        const allCheckbox = document.getElementById('user-filter-all');
        if (allCheckbox && !allCheckbox.checked && userIds) {
            params.append('users', userIds);
        }

        Promise.all([
            fetch(`invoices.php?ajax=receipts&${params.toString()}`).then(res => res.text()),
            fetch(`invoices.php?ajax=pagination&${params.toString()}`).then(res => res.text())
        ])
            .then(([receiptsHtml, paginationHtml]) => {
                loader.style.display = 'none';
                grid.innerHTML = receiptsHtml;
                if (pagination) pagination.innerHTML = paginationHtml;
                const selectAllCb = document.getElementById('selectAllInvoices');
                if (selectAllCb) selectAllCb.checked = false;
                if (bulkSelectActive) {
                    document.querySelectorAll('.invoice-checkbox-container').forEach(el => el.classList.add('show'));
                }
            })
            .catch(err => {
                loader.style.display = 'none';
                grid.innerHTML = '<div class="empty-state" style="grid-column: 1 / -1; text-align: center; padding: 40px; color: red;">ເກີດຂໍ້ຜິດພາດໃນການໂຫຼດຂໍ້ມູນ</div>';
                console.error(err);
            });
    }

    function loadReceipts() {
        loadReceiptsPage(1);
    }

    function resetFilters() {
        document.getElementById('searchInput').value = '';
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('dateFrom').value = today;
        document.getElementById('dateTo').value = today;

        // Clear local storage dates on reset
        localStorage.removeItem('invoice_date_from');
        localStorage.removeItem('invoice_date_to');

        // Reset users filter
        const allCheckbox = document.getElementById('user-filter-all');
        if (allCheckbox) {
            allCheckbox.checked = true;
            toggleAllUsers(allCheckbox);
        } else {
            loadReceipts();
        }
    }

    function openInvoiceModal(element) {
        const modal = document.getElementById('invoiceModal');
        const modalContent = document.getElementById('modalInvoiceContent');

        // Find the actual receipt element inside the clicked wrapper
        const receiptEl = element.querySelector('.receipt') || element.querySelector('.receipt-pos');

        if (receiptEl) {
            // Clone the element so we don't move it from the grid
            const clonedReceipt = receiptEl.cloneNode(true);

            // Clear existing content and append new
            modalContent.innerHTML = '';
            modalContent.appendChild(clonedReceipt);

            // Extract the order ID for printing (from the bill number info-value)
            // It's a bit tricky, let's grab it from the first info-value or pos-meta
            let orderId = '';
            const inforow = clonedReceipt.querySelector('.first-row .info-value');
            if (inforow) {
                orderId = inforow.textContent.trim();
            } else {
                const posmeta = clonedReceipt.querySelector('.pos-meta strong');
                if (posmeta && posmeta.nextSibling) {
                    orderId = posmeta.nextSibling.textContent.trim();
                }
            }

            currentOrderIdToPrint = orderId;

            // Update the print button action
            document.getElementById('printModalBtn').onclick = (e) => {
                e.stopPropagation();
                if (currentOrderIdToPrint) {
                    printSpecificOrder(currentOrderIdToPrint);
                }
            };

            // Show modal
            modal.classList.add('show');
            document.body.style.overflow = 'hidden'; // Prevent page scrolling
        }
    }

    function toggleBulkSelect() {
        bulkSelectActive = true;
        document.getElementById('toggle-bulk-select').style.display = 'none';
        document.getElementById('bulk-actions').classList.add('show');
        document.querySelectorAll('.invoice-checkbox-container').forEach(el => el.classList.add('show'));
    }

    function cancelBulkSelect() {
        bulkSelectActive = false;
        document.getElementById('toggle-bulk-select').style.display = 'inline-flex';
        document.getElementById('bulk-actions').classList.remove('show');
        document.querySelectorAll('.invoice-checkbox-container').forEach(el => el.classList.remove('show'));
        document.querySelectorAll('.invoice-checkbox').forEach(cb => cb.checked = false);
        const selectAllCb = document.getElementById('selectAllInvoices');
        if (selectAllCb) selectAllCb.checked = false;
    }

    function toggleCheckbox(wrapperElement, event) {
        if (!bulkSelectActive) {
            openInvoiceModal(wrapperElement);
            return;
        }
        // Find the checkbox inside this wrapper
        const checkbox = wrapperElement.querySelector('.invoice-checkbox');
        if (checkbox) {
            checkbox.checked = !checkbox.checked;
            updateSelectAllCheckboxState();
        }
    }

    function toggleAllInvoices(labelElement) {
        const selectAllCb = document.getElementById('selectAllInvoices');
        const isChecked = selectAllCb.checked;
        const checkboxes = document.querySelectorAll('.invoice-checkbox');
        checkboxes.forEach(cb => cb.checked = isChecked);
    }

    function updateSelectAllCheckboxState() {
        const checkboxes = document.querySelectorAll('.invoice-checkbox');
        const selectAllCb = document.getElementById('selectAllInvoices');
        if (checkboxes.length === 0) {
            selectAllCb.checked = false;
            return;
        }
        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
        selectAllCb.checked = allChecked;
    }

    let bulkSelectActive = false;

    // Call this after loading receipts
    const originalLoadReceiptsThen = window.loadReceiptsThen || function () { };
    // Let's hook into loadReceipts end to reset select all checkbox
    // Already updating it inline isn't easy, instead we will rely on DOM changes.
    // We can use a MutationObserver or just reset it when a new fetch happens.

    function closeInvoiceModal(event) {
        // Only close if clicking the backdrop or close button, not the receipt itself
        if (event) {
            const target = event.target;
            if (target.id === 'invoiceModal' || target.closest('.close-modal-btn')) {
                const modal = document.getElementById('invoiceModal');
                modal.classList.remove('show');
                document.body.style.overflow = ''; // Restore scrolling
            }
        } else {
            const modal = document.getElementById('invoiceModal');
            modal.classList.remove('show');
            document.body.style.overflow = '';
        }
    }

    // Print a specific order by opening print_invoice.php in a hidden iframe (or small popup)
    function printSpecificOrder(orderId) {
        if (!orderId) return;

        // Using a popup window is more reliable for triggering the print dialog
        const printWindow = window.open(`print_invoice.php?id=${orderId}`, 'PrintWindow', 'width=800,height=600');
        // The print_invoice.php script auto-prints on load via JS
    }

    // Print selected or all matching
    function printSelectedOrAll() {
        let orderIds = [];

        if (bulkSelectActive) {
            const checkedBoxes = document.querySelectorAll('.invoice-checkbox:checked');
            if (checkedBoxes.length > 0) {
                checkedBoxes.forEach(cb => orderIds.push(cb.value));
            } else {
                Swal.fire({
                    icon: 'warning',
                    title: 'ບໍ່ໄດ້ເລືອກຂໍ້ມູນ',
                    text: 'ກະລຸນາເລືອກໃບບິນທີ່ຕ້ອງການພິມ',
                    confirmButtonText: 'ຕົກລົງ'
                });
                return;
            }
        } else {
            // Collect all order IDs from the currently displayed grid if none selected
            const wrappers = document.querySelectorAll('.invoice-thumbnail-wrapper');
            wrappers.forEach(wrap => {
                const cb = wrap.querySelector('.invoice-checkbox');
                if (cb) {
                    orderIds.push(cb.value);
                }
            });
        }

        if (orderIds.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'ບໍ່ມີຂໍ້ມູນ',
                text: 'ບໍ່ພົບບິນໃນລາຍຊື່ທີ່ສະແດງ',
                confirmButtonText: 'ຕົກລົງ'
            });
            return;
        }

        if (orderIds.length > 50) {
            Swal.fire({
                icon: 'warning',
                title: 'ພິມຫຼາຍເກີນໄປ',
                text: 'ກະລຸນາພິມເທື່ອລະໜ້ອຍກວ່າ 50 ບິນ',
                confirmButtonText: 'ຕົກລົງ'
            });
            return;
        }

        const params = orderIds.join(',');
        const printWindow = window.open(`print_invoice.php?order_ids=${params}`, 'PrintWindow', 'width=800,height=600');
    }

    // Handle Escape key to close modal
    document.addEventListener('keydown', function (event) {
        if (event.key === "Escape") {
            closeInvoiceModal();
        }
    });

</script>

<?php require_once '../includes/footer.php'; ?>