<?php

require_once __DIR__ . '/navbar.php';
$pdo = require __DIR__ . '/../config/db.php';
if (session_status() === PHP_SESSION_NONE) session_start();
$role = $_SESSION['role'] ?? null;
if ($role !== 'admin' && $role !== 'staff') {
    header('Location: ../ooh_project/index.php?page=login');
    exit;
}

$sites = $pdo->query('SELECT * FROM sites ORDER BY id DESC')->fetchAll();
?>
<!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.0">
    <title>OOH Management</title>
    <link rel="icon" type="image/x-icon" href="../ooh_project/favicon.ico">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .table-row-even {
            background-color: #fff;
        }

        .table-row-odd {
            background-color: #f6f6f6;
        }

        .table-hover>tbody>tr.table-row-even:hover,
        .table-hover>tbody>tr.table-row-odd:hover {
            background-color: #e9ecef !important;
        }

        .eval-img {
            max-width: 100%;
            max-height: 220px;
            border-radius: 8px;
        }

        .modal-xl {
            max-width: 1100px;
        }

        /* Add this for criteria modal table font size */
        #evaluateModal .table,
        #evaluateModal .table th,
        #evaluateModal .table td,
        #evaluateModal .form-control-sm {
            font-size: 0.8rem !important;
        }

        #evaluateModal .table tbody tr {
            height: 28px !important;
            /* Reduce row height (default ~35px, now ~80% of that) */
            line-height: 1.1 !important;
            padding-top: 0 !important;
            padding-bottom: 0 !important;
        }

        #evaluateModal .table td,
        #evaluateModal .table th {
            padding-top: 2px !important;
            padding-bottom: 2px !important;
            vertical-align: middle !important;
        }
    </style>
    <style>
        body,
        html,
        .container,
        .card,
        .modal-content,
        .table,
        .form-control,
        .btn,
        .modal-title,
        .fw-bold,
        .text-primary,
        .text-light {
            font-family: 'Arial Unicode MS', Arial, Helvetica, sans-serif !important;
        }
    </style>
</head>

<body style="background-color: #efefef;">
    <div class="container mt-2">
        <h2 class="mb-2 w-100 text-center text-dark d-inline-block" style="position:relative;">
            Site Evaluation
        </h2>

        <!-- Search & Filter Bar OUTSIDE the table -->
        <div class="card card-body mb-3 p-2" style="background:#f8f9fa;">
            <div class="row g-2 align-items-center">
                <div class="col-12 col-md-2 mt-2 mt-md-0">
                    <div class="d-flex align-items-center" style="padding: 0.7rem 0.7rem 0 0.7rem;">
                        <span class="fw-bold text-primary me-2" style="font-size:1.05em;">Smart Search</span>
                        <button type="button" id="clearFiltersBtn" class="btn btn-light btn-sm border ms-1" style="padding:0.2rem 0.5rem;line-height:1;" title="Clear all filters">
                            <img src="https://cdn-icons-png.flaticon.com/512/1828/1828778.png" alt="Clear" style="width:18px;height:18px;vertical-align:middle;">
                        </button>
                    </div>
                </div>
                <div class="col-6 col-md-2">
                    <input type="text" class="form-control form-control-sm" id="filterSupplier" placeholder="By Supplier">
                </div>
                <div class="col-6 col-md-2">
                    <input type="text" class="form-control form-control-sm" id="filterFormat" placeholder="By Format">
                </div>
                <div class="col-6 col-md-2">
                    <input type="text" class="form-control form-control-sm" id="filterAddress" placeholder="By Address">
                </div>
                <div class="col-6 col-md-2">
                    <input type="text" class="form-control form-control-sm" id="filterDistrict" placeholder="By District">
                </div>
                <div class="col-6 col-md-2">
                    <input type="text" class="form-control form-control-sm" id="filterMarket" placeholder="By Market">
                </div>

            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-bordered table-hover" style="font-size:0.9rem;">

                <thead class="table-dark">
                    <tr>
                        <th class="text-center">Supplier</th>
                        <th class="text-center">Type</th>
                        <th class="text-center">Format</th>
                        <th class="text-center">Size (m)</th>
                        <th class="text-center">Size (px)</th>
                        <th class="text-center">Image</th>
                        <th class="text-center">Location</th>
                        <th class="text-center">Score</th>
                        <th class="text-center">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($sites as $i => $site): ?>
                        <tr class="format-row<?= $i % 2 === 0 ? ' table-row-even' : ' table-row-odd' ?>"
                            data-supplier="<?= htmlspecialchars($site['supplier']) ?>"
                            data-format="<?= htmlspecialchars($site['format']) ?>"
                            data-address="<?= htmlspecialchars(($site['street_no'] ? 'No. ' . $site['street_no'] . ' ' : '') . ($site['street'] ?? '')) ?>"
                            data-district="<?= htmlspecialchars($site['district'] ?? '') ?>"
                            data-market="<?= htmlspecialchars($site['market'] ?? '') ?>">
                            <td class="align-middle text-center"><?= htmlspecialchars($site['supplier']) ?></td>
                            <td class="align-middle text-center"><?= htmlspecialchars($site['type']) ?></td>
                            <td class="align-middle text-center"><?= htmlspecialchars($site['format']) ?></td>
                            <td class="align-middle text-center"><?= htmlspecialchars($site['size_x_m']) ?> x <?= htmlspecialchars($site['size_y_m']) ?></td>
                            <td class="align-middle text-center"><?= htmlspecialchars($site['size_x_p']) ?> x <?= htmlspecialchars($site['size_y_p']) ?></td>
                            <td class="align-middle text-center">
                                <?php if ($site['image_base']): ?>
                                    <img
                                        src="/ooh_project/media/<?= htmlspecialchars($site['image_base']) ?>"
                                        class="eval-img"
                                        style="max-width:60px;max-height:40px;margin-top:1px;cursor:pointer;border-radius:0;"
                                        onmouseenter="showCustomImageTooltip(event, '/ooh_project/media/<?= htmlspecialchars($site['image_base']) ?>')"
                                        onmouseleave="hideCustomImageTooltip()">
                                <?php endif; ?>
                            </td>
                            <td class="align-middle text-center">
                                <?php
                                $loc = '';
                                if ($site['street_no']) $loc .= 'No. ' . $site['street_no'] . ' ';
                                if ($site['street']) $loc .= $site['street'] . ', ';
                                if ($site['ward']) $loc .= 'Ward ' . $site['ward'] . ', ';
                                if ($site['district']) $loc .= 'Dist. ' . $site['district'] . ', ';
                                if ($site['market']) $loc .= $site['market'];
                                $mapLink = $site['site_coordination'] ? $site['site_coordination'] : 'https://www.google.com/maps/search/' . urlencode($loc);
                                ?>
                                <a href="<?= htmlspecialchars($mapLink) ?>" target="_blank" style="font-size:0.95em;text-decoration:none;color:inherit;" title="Click to view map">
                                    <?= htmlspecialchars($loc) ?>
                                </a>
                            </td>
                            <td class="align-middle text-center"><?= htmlspecialchars($site['evaluate_score']) ?></td>
                            <td class="align-middle text-center">
                                <div class="d-flex align-items-center justify-content-center gap-1">
                                    <?php if (empty($site['evaluate_score'])): ?>
                                        <button class="btn btn-sm" style="color:#fff;padding:2px 6px; background-color: #74deecff;" onclick="openEvaluateModal(<?= $site['id'] ?>)" title="Evaluate">
                                            <img src="https://cdn-icons-png.flaticon.com/512/5431/5431453.png" alt="Evaluate" style="width:18px;height:18px;">
                                        </button>
                                    <?php else: ?>
                                        <button class="btn btn-sm bg-warning" style="color:#fff;padding:2px 6px;" onclick="openEditModal(<?= $site['id'] ?>)" title="Edit">
                                            <img src="https://cdn-icons-png.flaticon.com/512/1159/1159633.png" alt="Edit" style="width:18px;height:18px;filter:brightness(1.2);">
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>

                </tbody>
            </table>
        </div>
    </div>
    <style>
        .table.table-bordered tr.table-row-even {
            background-color: #fff !important;
            --bs-table-bg: #fff !important;
        }

        .table.table-bordered tr.table-row-odd {
            background-color: #f6f6f6 !important;
            --bs-table-bg: #f6f6f6 !important;
        }

        .table.table-bordered.table-hover>tbody>tr.table-row-even:hover,
        .table.table-bordered.table-hover>tbody>tr.table-row-odd:hover {
            background-color: #e9ecef !important;
            --bs-table-bg: #e9ecef !important;
        }

        .table> :not(caption)>*>* {
            vertical-align: middle;
            text-align: center;
        }

        .table>tbody>tr {
            height: 40px;
        }

        .table>tbody>tr>td {
            max-width: 100%;
            /* Adjust as needed for your layout */
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            vertical-align: middle;
        }

        #custom-img-tooltip {
            display: none;
            position: fixed;
            z-index: 9999;
            pointer-events: none;
            background: #fff;
            border: 1px solid #bbb;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
            padding: 4px;
            border-radius: 6px;
        }

        #custom-img-tooltip img {
            max-width: 640px;
            max-height: 480px;
            display: block;
        }
    </style>
    <div id="custom-img-tooltip"></div>

    <!-- Evaluate Modal -->
    <div class="modal fade" id="evaluateModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header" style="background-color: #c2d7ff; color: #fff;">
                    <h5 class="modal-title text-dark" style="padding-left: 0.8rem;">Evaluate Site</h5>
                    <button type="button" id="benchmarkInfoBtn" class="btn ms-2 align-baseline"
                        style="vertical-align:middle;background:none;border:none;padding-left: 20rem;"
                        title="Show Benchmarking Criteria">
                        <img src="https://cdn-icons-png.flaticon.com/512/4923/4923175.png" alt="Benchmarking"
                            style="width:48px;height:48px;filter:invert(18%) sepia(80%) saturate(7470%) hue-rotate(246deg) brightness(0.95);">
                    </button>
                    <div id="benchmark-img-tooltip" style="display:none;position:fixed;z-index:99999;pointer-events:none;">
                        <img src="/ooh_project/modules/support/site_evaluate.png" style="max-width:1000px;box-shadow:0 8px 32px rgba(0,0,0,0.28),0 1.5px 8px rgba(0,0,0,0.12);border:2px solid #e0e0ff;background:#fff;">
                    </div>
                    <button type="button" style="padding-right: 0.8rem;" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-6" id="eval-image"></div>
                        <div class="col-md-6" id="eval-map"></div>
                    </div>
                    <form id="evaluateForm">
                        <div class="row">
                            <div class="col-12 col-md-6">
                                <div class="table-responsive">
                                    <table class="table table-bordered mt-3">
                                        <thead>
                                            <tr>
                                                <th class="text-light bg-dark">Criteria</th>
                                                <th class="text-light bg-dark">Weight</th>
                                                <th class="text-light bg-dark">Mark (1-4)</th>
                                            </tr>
                                        </thead>
                                        <tbody id="eval-criteria-body-left"></tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="col-12 col-md-6">
                                <div class="table-responsive">
                                    <table class="table table-bordered mt-3">
                                        <thead>
                                            <tr>
                                                <th class="text-light bg-dark">Criteria</th>
                                                <th class="text-light bg-dark">Weight</th>
                                                <th class="text-light bg-dark">Mark (1-4)</th>
                                            </tr>
                                        </thead>
                                        <tbody id="eval-criteria-body-right"></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="row align-items-center">
                            <div class="col-12 col-md-6 mb-2 mb-md-0">
                                <div class="fw-bold">Total Weighted Score: <span id="eval-total-score">0</span></div>
                            </div>
                            <div class="col-12 col-md-6 text-md-end">
                                <input type="hidden" name="site_id" id="eval-site-id">
                                <button type="submit" class="btn btn-success">Update Score</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Show benchmarking image tooltip on mouseover
        const benchmarkBtn = document.getElementById('benchmarkInfoBtn');
        const benchmarkTooltip = document.getElementById('benchmark-img-tooltip');

        benchmarkBtn.addEventListener('mouseenter', function(e) {
            benchmarkTooltip.style.display = 'block';
            positionBenchmarkTooltip(e);
        });
        benchmarkBtn.addEventListener('mousemove', function(e) {
            positionBenchmarkTooltip(e);
        });
        benchmarkBtn.addEventListener('mouseleave', function() {
            benchmarkTooltip.style.display = 'none';
        });

        function positionBenchmarkTooltip(e) {
            const img = benchmarkTooltip.querySelector('img');
            const imgWidth = Math.min(1000, window.innerWidth * 0.95);
            img.style.maxWidth = imgWidth + 'px';

            // Center horizontally, below the mouse
            const left = Math.max(10, Math.min(window.innerWidth - imgWidth - 10, e.clientX - imgWidth / 2));
            let top = e.clientY + 20;
            // Prevent overflow bottom
            const tooltipHeight = img.offsetHeight || 400;
            if (top + tooltipHeight > window.innerHeight) {
                top = window.innerHeight - tooltipHeight - 10;
            }
            benchmarkTooltip.style.left = left + 'px';
            benchmarkTooltip.style.top = top + 'px';
        }
    </script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Example criteria (customize as needed)
        const evalCriteria = [{
                key: 'ad_form',
                label: 'Ad Form [Loại Hình]',
                weight: 0.03
            },
            {
                key: 'ad_size',
                label: 'Ad Size [Kích Thước]',
                weight: 0.03
            },
            {
                key: 'structure',
                label: 'Structure [Kết Cấu]',
                weight: 0.05
            },
            {
                key: 'view_height',
                label: 'Viewing Height [Chiều Cao Bảng]',
                weight: 0.04
            },
            {
                key: 'vision',
                label: 'Vision Distance [Tầm Nhìn Xa]',
                weight: 0.07
            },
            {
                key: 'angel',
                label: 'Angel of Vision [Góc Nhìn]',
                weight: 0.05
            },
            {
                key: 'traffic_flow',
                label: 'Traffic Flow [Lưu Lượng Giao Thông]',
                weight: 0.2
            },
            {
                key: 'traffic_speed',
                label: 'Traffic Speed [Tốc Độ Lưu Thông]',
                weight: 0.02
            },
            {
                key: 'road_num',
                label: 'Number of Road [Số Lượng Đường Có Thể Thấy]',
                weight: 0.03
            },
            {
                key: 'road_type',
                label: 'Road Type [Loại Đường]',
                weight: 0.02
            },
            {
                key: 'visual_clutter',
                label: 'Visual Clutter [Yếu Tố Xao Nhãng]',
                weight: 0.03
            },
            {
                key: 'vision_block',
                label: 'Vision Block [Vướng Tầm Nhìn]',
                weight: 0.1
            },
            {
                key: 'surrounding',
                label: 'Surrounding Area [Địa Danh Xung Quanh]',
                weight: 0.02
            },
            {
                key: 'obstruct',
                label: 'Obstruction [Kẹt Xe]',
                weight: 0.02
            },
            {
                key: 'zone',
                label: 'Zone [Khu Vực]',
                weight: 0.15
            },
            {
                key: 'roundabout_cross',
                label: 'Roundabout/ Crossroad [Vòng Xuyến/ Ngã Tư]',
                weight: 0.08
            },
            {
                key: 'traffic_light',
                label: 'Traffic Light [Đèn Giao Thông]',
                weight: 0.02
            },
            {
                key: 'illumination',
                label: 'Illumination [Chiếu Sáng]',
                weight: 0.04
            }
        ];

        // Save evaluation data to JSON before updating DB
        function saveEvaluationToJson(siteId, criteriaData, callback) {
            fetch('/ooh_project/handler/save_evaluation_json.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        site_id: siteId,
                        criteria: criteriaData
                    })
                })
                .then(res => res.json())
                .then(callback);
        }

        // Open Evaluate Modal for both Evaluate and Edit
        function showEvaluateModal(siteId, isEdit = false) {
            fetch('/ooh_project/handler/format_crud.php', {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json'
                    },
                    body: new URLSearchParams({
                        action: 'get',
                        id: siteId
                    })
                })
                .then(res => res.json())
                .then(data => {
                    const f = data.format;
                    document.getElementById('eval-image').innerHTML = f.image_base ?
                        `<img src="/ooh_project/media/${f.image_base}" class="img-fluid eval-img" style="max-height:250px;">` :
                        '<span>No image</span>';
                    document.getElementById('eval-map').innerHTML =
                        `<iframe width="100%" height="250" frameborder="0" style="border:0"
                src="https://www.google.com/maps?q=${encodeURIComponent(f.format_coordination || (f.street + ' ' + f.ward + ' ' + f.district + ' ' + f.market))}&output=embed" allowfullscreen></iframe>`;
                    document.getElementById('eval-site-id').value = f.id;

                    // Try to load previous evaluation if editing
                    if (isEdit) {
                        fetch('/ooh_project/handler/load_evaluation_json.php?site_id=' + siteId)
                            .then(res => res.json())
                            .then(json => renderCriteriaInputs(json))
                            .catch(() => renderCriteriaInputs(null));
                    } else {
                        renderCriteriaInputs(null);
                    }

                    function renderCriteriaInputs(json) {
                        let leftRows = '',
                            rightRows = '';
                        const half = Math.ceil(evalCriteria.length / 2);
                        evalCriteria.forEach((c, idx) => {
                            let val = (json && json[c.key] !== undefined) ? json[c.key] : 1;
                            const row = `<tr style="max-height: 50px; overflow: hidden;">
                    <td>${c.label}</td>
                    <td>${(c.weight * 100).toFixed(0)}%</td>
                    <td><input type="number" min="1" max="4" step="1" class="form-control form-control-sm eval-mark" name="${c.key}" data-weight="${c.weight}" value="${val}"></td>
                </tr>`;
                            if (idx < half) leftRows += row;
                            else rightRows += row;
                        });
                        document.getElementById('eval-criteria-body-left').innerHTML = leftRows;
                        document.getElementById('eval-criteria-body-right').innerHTML = rightRows;
                        document.getElementById('eval-total-score').textContent = '0';

                        // Attach score calculation
                        document.querySelectorAll('.eval-mark').forEach(input => {
                            input.addEventListener('input', calcEvalScore);
                        });
                        calcEvalScore();
                    }

                    // Show modal
                    new bootstrap.Modal(document.getElementById('evaluateModal')).show();
                });
        }

        // Attach to both buttons
        window.openEvaluateModal = function(siteId) {
            showEvaluateModal(siteId, false);
        }
        window.openEditModal = function(siteId) {
            showEvaluateModal(siteId, true);
        }

        // Submit handler: save to JSON then update DB
        document.getElementById('evaluateForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const site_id = document.getElementById('eval-site-id').value;
            const score = document.getElementById('eval-total-score').textContent;
            // Collect all criteria values
            let criteriaData = {};
            document.querySelectorAll('.eval-mark').forEach(input => {
                criteriaData[input.name] = input.value;
            });
            // Save to JSON, then update DB
            saveEvaluationToJson(site_id, criteriaData, function(resp) {
                fetch('/ooh_project/handler/update_score.php', {
                        method: 'POST',
                        body: new URLSearchParams({
                            site_id,
                            score
                        })
                    })
                    .then(res => res.text())
                    .then(resp => {
                        showMessageModal('Score updated!', 'success', function() {
                            location.reload();
                        });
                    })
                    .catch(() => {
                        showMessageModal('Server error.', 'danger');
                    });
            });
        });


        function calcEvalScore() {
            let total = 0;
            document.querySelectorAll('.eval-mark').forEach(input => {
                const mark = parseFloat(input.value) || 0;
                const weight = parseFloat(input.dataset.weight) || 0;
                total += mark * weight;
            });
            document.getElementById('eval-total-score').textContent = total.toFixed(2);
        }

        document.getElementById('evaluateForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const site_id = document.getElementById('eval-site-id').value;
            const score = document.getElementById('eval-total-score').textContent;
            fetch('/ooh_project/handler/update_score.php', {
                    method: 'POST',
                    body: new URLSearchParams({
                        site_id,
                        score
                    })
                })
                .then(res => res.text())
                .then(resp => {
                    showMessageModal('Score updated!', 'success', function() {
                        location.reload();
                    });
                })
                .catch(() => {
                    showMessageModal('Server error.', 'danger');
                });
        });

        // Enable Bootstrap tooltip for title and images
        document.addEventListener('DOMContentLoaded', function() {
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            tooltipTriggerList.forEach(function(tooltipTriggerEl) {
                new bootstrap.Tooltip(tooltipTriggerEl);
            });
        });

        // Show benchmarking modal below mouse and centered horizontally
        document.getElementById('benchmarkInfoBtn').addEventListener('click', function(e) {
            var modal = new bootstrap.Modal(document.getElementById('benchmarkModal'));
            modal.show();

            // Wait for modal to show, then position
            setTimeout(function() {
                var dialog = document.getElementById('benchmarkModalDialog');
                var body = document.getElementById('benchmarkModalBody');
                dialog.style.position = 'fixed';
                dialog.style.margin = '0';
                dialog.style.left = '50%';
                dialog.style.transform = 'translateX(-50%)';
                dialog.style.top = (e.clientY + 20) + 'px';
                dialog.style.pointerEvents = 'auto';
                body.style.background = 'transparent';
            }, 150);
        });

        // Hide modal resets position (optional, for safety)
        document.getElementById('benchmarkModal').addEventListener('hidden.bs.modal', function() {
            var dialog = document.getElementById('benchmarkModalDialog');
            dialog.style.position = '';
            dialog.style.left = '';
            dialog.style.top = '';
            dialog.style.transform = '';
        });
    </script>
    <script>
        // Custom image tooltip logic
        function showCustomImageTooltip(e, imgSrc) {
            let tooltip = document.getElementById('custom-img-tooltip');
            tooltip.innerHTML = "<img src='" + imgSrc + "'>";
            tooltip.style.display = 'block';
            positionCustomTooltip(e);
        }

        function hideCustomImageTooltip() {
            let tooltip = document.getElementById('custom-img-tooltip');
            tooltip.style.display = 'none';
        }

        function positionCustomTooltip(e) {
            let tooltip = document.getElementById('custom-img-tooltip');
            let x = e.clientX + 20;
            let y = e.clientY + 20;
            // Prevent overflow right/bottom
            let w = tooltip.offsetWidth || 640;
            let h = tooltip.offsetHeight || 480;
            if (x + w > window.innerWidth) x = window.innerWidth - w - 10;
            if (y + h > window.innerHeight) y = window.innerHeight - h - 10;
            tooltip.style.left = x + 'px';
            tooltip.style.top = y + 'px';
        }
        document.addEventListener('mousemove', function(e) {
            let tooltip = document.getElementById('custom-img-tooltip');
            if (tooltip.style.display === 'block') {
                positionCustomTooltip(e);
            }
        });

        // --- FIXED FILTER FUNCTIONALITY ---
        function filterTable() {
            var supplier = document.getElementById('filterSupplier').value.trim().toLowerCase();
            var format = document.getElementById('filterFormat').value.trim().toLowerCase();
            var address = document.getElementById('filterAddress').value.trim().toLowerCase();
            var district = document.getElementById('filterDistrict').value.trim().toLowerCase();
            var market = document.getElementById('filterMarket').value.trim().toLowerCase();

            var rows = document.querySelectorAll('.format-row');
            rows.forEach(function(row) {
                var supplierVal = (row.getAttribute('data-supplier') || '').toLowerCase();
                var formatVal = (row.getAttribute('data-format') || '').toLowerCase();
                var addressVal = (row.getAttribute('data-address') || '').toLowerCase();
                var districtVal = (row.getAttribute('data-district') || '').toLowerCase();
                var marketVal = (row.getAttribute('data-market') || '').toLowerCase();

                var show = true;
                if (supplier && !supplierVal.includes(supplier)) show = false;
                if (format && !formatVal.includes(format)) show = false;
                if (address && !addressVal.includes(address)) show = false;
                if (district && !districtVal.includes(district)) show = false;
                if (market && !marketVal.includes(market)) show = false;
                row.style.display = show ? '' : 'none';
            });
        }

        // Attach filter events robustly
        ['filterSupplier', 'filterFormat', 'filterAddress', 'filterDistrict', 'filterMarket'].forEach(function(id) {
            var el = document.getElementById(id);
            if (el) el.addEventListener('input', filterTable);
        });
        var clearBtn = document.getElementById('clearFiltersBtn');
        if (clearBtn) {
            clearBtn.onclick = function() {
                ['filterSupplier', 'filterFormat', 'filterAddress', 'filterDistrict', 'filterMarket'].forEach(function(id) {
                    var el = document.getElementById(id);
                    if (el) el.value = '';
                });
                filterTable();
            };
        }
    </script>
    <!-- Active Message Modal -->
    <?php include __DIR__ . '/common.php'; ?>
    <script src="/ooh_project/modules/common.js"></script>
</body>

</html>