<?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>Site Evaluation</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;
        }
    </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-4 ">
    <h2 class="mb-4 text-center text-dark d-inline-block" style="position:relative;">
        Site Evaluation
        <button type="button" id="benchmarkInfoBtn" class="btn p-0 ms-2 align-baseline" style="vertical-align:middle;background:none;border:none;" title="Show Benchmarking Criteria">
            <img src="https://cdn-icons-png.flaticon.com/512/3132/3132693.png" alt="Benchmarking" style="width:28px;height:28px;filter:invert(18%) sepia(80%) saturate(7470%) hue-rotate(246deg) brightness(0.95);">
        </button>
    </h2>
    <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>
        <tr>
            <td><input type="text" class="form-control form-control-sm" id="filterSupplier" placeholder="By Supplier"></td>
            <td><input type="text" class="form-control form-control-sm" id="filterType" placeholder="By Type"></td>
            <td><input type="text" class="form-control form-control-sm" id="filterFormat" placeholder="By Format"></td>
            <td><input type="text" class="form-control form-control-sm" id="filterAddress" placeholder="By Address"></td>
            <td><input type="text" class="form-control form-control-sm" id="filterDistrict" placeholder="By District"></td>
            <td><input type="text" class="form-control form-control-sm" id="filterMarket" placeholder="By Market"></td>
            <td colspan="2"></td>
            <td>
                <div class="d-flex align-items-center justify-content-md-start justify-content-center mb-2 mb-md-0">
                    <span class="fw-bold text-primary me-2" style="font-size:1.15em; letter-spacing:1px;">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>
            </td> 
        </tr>
        <tbody>
        <?php foreach ($sites as $i => $site): ?>
            <tr class="format-row<?= $i % 2 === 0 ? ' table-row-even' : ' table-row-odd' ?>">
                <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_y']) ?></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:40px;max-height:20px;margin-top:4px;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 = trim(($site['street'] ?? '') . ' ' . ($site['ward'] ? 'Ward ' . $site['ward'] . ' ' : '') . ($site['district'] ? 'Dist. ' . $site['district'] . ' ' : '') . ($site['market'] ?? ''));
                        $mapLink = $site['format_coordination'] ? $site['format_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="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">
                        <button class="btn btn-sm bg-primary" style="color:#fff;padding:2px 6px;" onclick="openEvaluateModal(<?= $site['id'] ?>)" title="Evaluate">
                            <img src="https://cdn-icons-png.flaticon.com/512/1828/1828884.png" alt="Evaluate" style="width:18px;height:18px;">
                            <!-- This icon is a white number "1" in a blue circle. You can change the number by using a different flaticon if needed. -->
                        </button>
                        <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>
                    </div>
                </td>
            </tr>
        <?php endforeach; ?>
        
        </tbody>
    </table>
</div>

<style>
.table-row-even {
    background-color: #fff !important;
}
.table-row-odd {
    background-color: #f6f6f6 !important;
}
.table-hover > tbody > tr.table-row-even:hover,
.table-hover > tbody > tr.table-row-odd:hover {
    background-color: #e9ecef !important;
}
.table > :not(caption) > * > * {
    vertical-align: middle;
    text-align: center;
}
</style>
<!-- Add this before </body> -->
<style>
#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: 320px;
    max-height: 240px;
    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">
        <h5 class="modal-title">Evaluate Site</h5>
        <button type="button" 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">
              <table class="table table-bordered mt-3">
                <thead>
                  <tr>
                    <th>Criteria</th>
                    <th>Weight</th>
                    <th>Mark (1-4)</th>
                  </tr>
                </thead>
                <tbody id="eval-criteria-body-left"></tbody>
              </table>
            </div>
            <div class="col-12 col-md-6">
              <table class="table table-bordered mt-3">
                <thead>
                  <tr>
                    <th>Criteria</th>
                    <th>Weight</th>
                    <th>Mark (1-4)</th>
                  </tr>
                </thead>
                <tbody id="eval-criteria-body-right"></tbody>
              </table>
            </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>

<!-- Benchmarking Modal -->
<div class="modal fade" id="benchmarkModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Site Evaluation Criteria</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body text-center">
        <img src="/ooh_project/site_evaluate.png" style="width:80%;max-width:900px;" alt="Site Evaluation Criteria">
      </div>
    </div>
  </div>
</div>

<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 }
];

function openEvaluateModal(siteId) {
    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;

        // Split criteria into two columns
        let leftRows = '', rightRows = '';
        const half = Math.ceil(evalCriteria.length / 2);
        evalCriteria.forEach((c, idx) => {
            const row = `<tr>
                <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="1"></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';

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

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

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 => {
        alert('Score updated!');
        location.reload();
    });
});

// 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 on icon click
document.getElementById('benchmarkInfoBtn').addEventListener('click', function() {
    var modal = new bootstrap.Modal(document.getElementById('benchmarkModal'));
    modal.show();
});
</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 || 320;
    let h = tooltip.offsetHeight || 240;
    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);
    }
});

// --- Filter/Search like update_database ---
function filterTable() {
    var supplier = document.getElementById('filterSupplier').value.trim().toLowerCase();
    var type = document.getElementById('filterType').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 cells = row.children;
        var supplierVal = (cells[0]?.textContent || '').toLowerCase();
        var typeVal = (cells[1]?.textContent || '').toLowerCase();
        var formatVal = (cells[2]?.textContent || '').toLowerCase();
        var addressVal = (cells[6]?.textContent || '').toLowerCase();

        // Extract district and market from addressVal
        var districtVal = '';
        var marketVal = '';
        var districtMatch = addressVal.match(/dist\.?\s*([^\s]+)/i);
        if (districtMatch && districtMatch[1]) districtVal = districtMatch[1].toLowerCase();

        var marketMatch = addressVal.match(/(?:dist\.[^ ]+\s*)?(.*)$/i);
        if (marketMatch && marketMatch[1]) marketVal = marketMatch[1].trim().toLowerCase();

        var show = true;
        if (supplier && !supplierVal.includes(supplier)) show = false;
        if (type && !typeVal.includes(type)) 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';
    });
}
['filterSupplier','filterType','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','filterType','filterFormat','filterAddress','filterDistrict','filterMarket'].forEach(function(id) {
            var el = document.getElementById(id);
            if (el) el.value = '';
        });
        filterTable();
    };
}
</script>
</body>
</html>