<?php
// competitor_activity.php - Manage competitor airing status on sites
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;
}
// Fetch competitors
$competitors = $pdo->query('SELECT * FROM competitors ORDER BY name')->fetchAll();
// Fetch sites
$sites = $pdo->query('SELECT * FROM sites ORDER BY id DESC')->fetchAll();
// Fetch activities with join
$activities = $pdo->query('SELECT ca.*, c.name AS competitor_name, s.supplier, s.format, s.size_x_m, s.size_y_m, s.size_x_p, s.size_y_p, s.market, s.image_base, s.street_no, s.street, s.ward, s.district, s.market AS site_market
    FROM comp_activity ca
    JOIN competitors c ON ca.competitor_id = c.id
    JOIN sites s ON ca.site = s.id
    ORDER BY ca.airing_time 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.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;
        }

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

        .modal-xl {
            max-width: 900px;
        }
    </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">Competitor Activity</h2>
        <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="filterCompetitor" placeholder="By Competitor (comma separated)">
                </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="filterMarket" placeholder="By Market">
                </div>
                <div class="col-6 col-md-2 text-end">
                    <button class="btn btn-success btn-sm" id="addActivityBtn">Add Activity</button>
                </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">Competitor</th>
                        <th class="text-center">Site</th>
                        <th class="text-center">Side Quantity</th>
                        <th class="text-center">Image</th>
                        <th class="text-center">Airing Time</th>
                        <th class="text-center">Estimate End</th>
                        <th class="text-center">Action</th>
                    </tr>
                </thead>
                <tbody id="activityTableBody">
                    <?php foreach ($activities as $i => $a): ?>
                        <tr class="activity-row<?= $i % 2 === 0 ? ' table-row-even' : ' table-row-odd' ?>" style="height:30px;"
                            data-competitor="<?= htmlspecialchars($a['competitor_name']) ?>"
                            data-supplier="<?= htmlspecialchars($a['supplier']) ?>"
                            data-format="<?= htmlspecialchars($a['format']) ?>"
                            data-market="<?= htmlspecialchars($a['site_market']) ?>"
                            data-size_x_m="<?= htmlspecialchars($a['size_x_m']) ?>"
                            data-size_y_m="<?= htmlspecialchars($a['size_y_m']) ?>"
                            data-size_x_p="<?= htmlspecialchars($a['size_x_p']) ?>"
                            data-size_y_p="<?= htmlspecialchars($a['size_y_p']) ?>">
                            <td class="align-middle text-center" style="font-weight:bold;"><?= htmlspecialchars($a['competitor_name']) ?></td>
                            <td class="align-middle text-center site-info-cell"
                                onmouseenter="showSiteTooltip(this, <?= htmlspecialchars(json_encode([
                                                                        'supplier' => $a['supplier'] ?? '',
                                                                        'format' => $a['format'] ?? '',
                                                                        'size_x_m' => $a['size_x_m'] ?? '',
                                                                        'size_y_m' => $a['size_y_m'] ?? '',
                                                                        'size_x_p' => $a['size_x_p'] ?? '',
                                                                        'size_y_p' => $a['size_y_p'] ?? '',
                                                                        'current_own' => $a['current_own'] ?? ''
                                                                    ])) ?>)"
                                onmouseleave="hideSiteTooltip()">
                                <?= htmlspecialchars($a['format']) ?> | <?= htmlspecialchars($a['street_no']) ?> <?= htmlspecialchars($a['street']) ?>, <?= htmlspecialchars($a['ward']) ?>, <?= htmlspecialchars($a['district']) ?>, <?= htmlspecialchars($a['site_market']) ?>
                                <?php
                                // Show badge if current_own matches a competitor name
                                $currentOwn = $a['current_own'] ?? '';
                                $competitorNames = array_map(function ($c) {
                                    return $c['name'];
                                }, $competitors);
                                if ($currentOwn && in_array($currentOwn, $competitorNames)) {
                                    echo '<span class="badge bg-danger ms-2">Competitor: ' . htmlspecialchars($currentOwn) . '</span>';
                                }
                                ?>
                            </td>
                            <td class="align-middle text-center">
                                <?= isset($a['side_no']) ? htmlspecialchars($a['side_no']) : '' ?>
                            </td>

                            <td class="align-middle text-center">
                                <?php if ($a['image_comp']): ?>
                                    <img src="/ooh_project/media/competitor/<?= htmlspecialchars($a['image_comp']) ?>" style="max-height:30px;cursor:pointer;"
                                        onmouseenter="showImageTooltip(this, '/ooh_project/media/competitor/<?= htmlspecialchars($a['image_comp']) ?>')" onmouseleave="hideImageTooltip()">
                                <?php endif; ?>
                            </td>
                            <td class="align-middle text-center">
                                <?= $a['airing_time'] ? date('Y-m-d', strtotime($a['airing_time'])) : '' ?>
                            </td>
                            <td class="align-middle text-center">
                                <?= $a['estimate_end'] ? date('Y-m-d', strtotime($a['estimate_end'])) : '' ?>
                            </td>
                            <td class="align-middle text-center">
                                <button class="btn btn-sm bg-warning" onclick="openEditActivityModal(<?= $a['id'] ?>)">Edit</button>
                                <button class="btn btn-sm bg-danger" onclick="deleteActivity(<?= $a['id'] ?>)">Delete</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <!-- Tooltip container outside all containers -->
    <div id="image-tooltip"><img id="image-tooltip-img" src="" style="max-width:300px;max-height:200px;"></div>
    <div id="site-tooltip" style="display:none;position:absolute;z-index:9999;background:#fff;border:1px solid #bbb;padding:10px;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.12);min-width:220px;"></div>
    <style>
        #image-tooltip {
            position: absolute;
            z-index: 9999;
            display: none;
            background: #fff;
            border: 1px solid #bbb;
            padding: 8px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
        }

        #site-tooltip {
            position: absolute;
            z-index: 9999;
            display: none;
            background: #fff;
            border: 1px solid #bbb;
            padding: 10px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
            min-width: 220px;
        }
    </style>
    <script>
        function showSiteTooltip(cell, data) {
            var tooltip = document.getElementById('site-tooltip');
            var html = '';
            if (data.supplier) html += '<div><b>Supplier:</b> ' + data.supplier + '</div>';
            if (data.format) html += '<div><b>Format:</b> ' + data.format + '</div>';
            if (data.size_x_m && data.size_y_m) html += '<div><b>Size:</b> ' + data.size_x_m + 'm x ' + data.size_y_m + 'm</div>';
            if (data.size_x_p && data.size_y_p) html += '<div><b>Size:</b> ' + data.size_x_p + 'px x ' + data.size_y_p + 'px</div>';
            if (data.current_own) html += '<div><b>Current Owner:</b> ' + data.current_own + '</div>';
            tooltip.innerHTML = html;
            tooltip.style.display = 'block';
            var rect = cell.getBoundingClientRect();
            tooltip.style.left = (rect.right + window.scrollX + 10) + 'px';
            tooltip.style.top = (rect.top + window.scrollY - 10) + 'px';
        }

        function hideSiteTooltip() {
            var tooltip = document.getElementById('site-tooltip');
            tooltip.style.display = 'none';
            tooltip.innerHTML = '';
        }

        function showImageTooltip(img, src) {
            var tooltip = document.getElementById('image-tooltip');
            var tooltipImg = document.getElementById('image-tooltip-img');
            tooltipImg.src = src;
            tooltipImg.style.maxWidth = '600px';
            tooltipImg.style.maxHeight = '400px';
            tooltip.style.display = 'block';
            // Use mouse event coordinates for accurate positioning
            img.onmousemove = function(e) {
                tooltip.style.left = (e.pageX + 10) + 'px';
                tooltip.style.top = (e.pageY + 10) + 'px';
            };
        }

        function hideImageTooltip() {
            var tooltip = document.getElementById('image-tooltip');
            var tooltipImg = document.getElementById('image-tooltip-img');
            tooltip.style.display = 'none';
            tooltipImg.style.maxWidth = '300px';
            tooltipImg.style.maxHeight = '200px';
        }
        window.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('img[onmouseenter]').forEach(function(img) {
                img.addEventListener('mouseenter', function(e) {
                    showImageTooltip(img, img.src);
                });
                img.addEventListener('mousemove', function(e) {
                    var tooltip = document.getElementById('image-tooltip');
                    tooltip.style.left = (e.pageX + 10) + 'px';
                    tooltip.style.top = (e.pageY + 10) + 'px';
                });
                img.addEventListener('mouseleave', function() {
                    hideImageTooltip();
                });
            });
        });
    </script>


    <!-- Add/Edit Modal -->
    <div class="modal fade" id="activityModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content" style="max-height:85vh;">
                <div class="modal-header" style="padding:0.5rem 1rem; background: linear-gradient(90deg, #007bff 60%, #0056b3 100%);">
                    <h5 class="modal-title text-white" id="activityModalTitle">Add Competitor Activity</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="activityForm" enctype="multipart/form-data">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label text-primary">Filter Sites</label>
                                <div class="row g-1 mb-2">
                                    <div class="col-6">
                                        <input type="text" class="form-control form-control-sm" id="modalFilterSupplier" placeholder="Supplier">
                                    </div>
                                    <div class="col-6">
                                        <input type="text" class="form-control form-control-sm" id="modalFilterFormat" placeholder="Format">
                                    </div>
                                    <div class="col-6 mt-1">
                                        <input type="text" class="form-control form-control-sm" id="modalFilterMarket" placeholder="Market">
                                    </div>
                                    <div class="col-6 mt-1">
                                        <input type="text" class="form-control form-control-sm" id="modalFilterDistrict" placeholder="District">
                                    </div>
                                    <div class="col-12 mt-1">
                                        <input type="text" class="form-control form-control-sm" id="modalFilterCompetitorOwn" placeholder="Current Owner (Competitor)">
                                    </div>
                                    <div class="col-12 mt-1">
                                        <input type="checkbox" id="modalFilterCompetitorOwned" class="form-check-input">
                                        <label for="modalFilterCompetitorOwned" class="form-check-label ms-1">Show only sites owned by competitors</label>
                                    </div>
                                    <div class="col-12 mt-2 text-end">
                                        <button type="button" class="btn btn-light btn-sm bg-primary text-light" id="modalClearFiltersBtn">Clear Filters</button>
                                    </div>
                                </div>
                                <label for="siteSelect" class="form-label text-primary">Site</label>
                                <select class="form-select" id="siteSelect" name="site_id" required style="width:100%;">
                                    <option value="">Select Site</option>
                                    <?php foreach ($sites as $s):
                                        $isCompetitorOwned = false;
                                        foreach ($competitors as $c) {
                                            if (isset($s['current_own']) && $s['current_own'] === $c['name']) {
                                                $isCompetitorOwned = true;
                                                break;
                                            }
                                        }
                                    ?>
                                        <option value="<?= $s['id'] ?>" data-supplier="<?= htmlspecialchars($s['supplier']) ?>" data-format="<?= htmlspecialchars($s['format']) ?>" data-market="<?= htmlspecialchars($s['market']) ?>" data-district="<?= htmlspecialchars($s['district']) ?>" data-current-own="<?= htmlspecialchars($s['current_own'] ?? '') ?>" data-competitor-owned="<?= $isCompetitorOwned ? '1' : '0' ?>" style="font-size:90%;">[<?= $s['id'] ?>] <?= htmlspecialchars($s['supplier']) ?> - <?= htmlspecialchars($s['format']) ?> - <?= htmlspecialchars($s['street']) ?>, <?= htmlspecialchars($s['ward']) ?>, <?= htmlspecialchars($s['district']) ?>, <?= htmlspecialchars($s['market']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <div id="siteInfo" class="mt-2"></div>
                                <label for="sideNo" class="form-label mt-2 text-primary">Side Quantity</label>
                                <input type="number" class="form-control" id="sideNo" name="side_no" min="1" required placeholder="Total of sides">
                            </div>
                            <div class="col-md-6">
                                <label for="competitorSelect" class="form-label text-primary">Competitor Name</label>
                                <select class="form-select" id="competitorSelect" name="competitor_id" required>
                                    <option value="">Select Competitor</option>
                                    <?php foreach ($competitors as $c): ?>
                                        <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <label for="imageComp" class="form-label mt-2 text-primary">Image of Competitor Aired</label>
                                <input type="file" class="form-control" id="imageComp" name="image_comp">
                                <label for="airingTime" class="form-label mt-2 text-primary">Airing Time</label>
                                <input type="date" class="form-control" id="airingTime" name="airing_time" required placeholder="YYYY-MM-DD">
                                <label for="estimateEnd" class="form-label mt-2 text-primary">Estimate End Time</label>
                                <input type="date" class="form-control" id="estimateEnd" name="estimate_end" placeholder="YYYY-MM-DD">
                                <div id="image-tooltip"><img id="image-tooltip-img" src="" style="max-width:300px;max-height:200px;"></div>
                                <small class="text-muted">Dont choose date if unknown of end date</small>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 text-end">
                                <input type="hidden" name="activity_id" id="activityId">
                                <button type="submit" class="btn btn-success">Save</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Modal site filter logic
        function filterSiteOptions() {
            var supplier = document.getElementById('modalFilterSupplier').value.trim().toLowerCase();
            var format = document.getElementById('modalFilterFormat').value.trim().toLowerCase();
            var market = document.getElementById('modalFilterMarket').value.trim().toLowerCase();
            var district = document.getElementById('modalFilterDistrict').value.trim().toLowerCase();
            var competitorOwn = document.getElementById('modalFilterCompetitorOwn').value.trim().toLowerCase();
            var competitorOwned = document.getElementById('modalFilterCompetitorOwned').checked;
            var select = document.getElementById('siteSelect');
            Array.from(select.options).forEach(function(opt, idx) {
                if (idx === 0) {
                    opt.style.display = '';
                    return;
                } // Always show 'Select Site'
                var show = true;
                if (supplier && !(opt.getAttribute('data-supplier') || '').toLowerCase().includes(supplier)) show = false;
                if (format && !(opt.getAttribute('data-format') || '').toLowerCase().includes(format)) show = false;
                if (market && !(opt.getAttribute('data-market') || '').toLowerCase().includes(market)) show = false;
                if (district && !(opt.getAttribute('data-district') || '').toLowerCase().includes(district)) show = false;
                if (competitorOwn && !(opt.getAttribute('data-current-own') || '').toLowerCase().includes(competitorOwn)) show = false;
                if (competitorOwned && opt.getAttribute('data-competitor-owned') !== '1') show = false;
                opt.style.display = show ? '' : 'none';
            });
        }
        ['modalFilterSupplier', 'modalFilterFormat', 'modalFilterMarket', 'modalFilterDistrict', 'modalFilterCompetitorOwned'].forEach(function(id) {
            var el = document.getElementById(id);
            if (el) el.addEventListener('input', filterSiteOptions);
            if (el && el.type === 'checkbox') el.addEventListener('change', filterSiteOptions);
        });
        // Add competitorOwn filter
        var competitorOwnInput = document.getElementById('modalFilterCompetitorOwn');
        if (competitorOwnInput) competitorOwnInput.addEventListener('input', filterSiteOptions);
        // Clear filter button logic
        var modalClearBtn = document.getElementById('modalClearFiltersBtn');
        if (modalClearBtn) {
            modalClearBtn.onclick = function() {
                ['modalFilterSupplier', 'modalFilterFormat', 'modalFilterMarket', 'modalFilterDistrict', 'modalFilterCompetitorOwn'].forEach(function(id) {
                    var el = document.getElementById(id);
                    if (el) el.value = '';
                });
                filterSiteOptions();
            };
        }
    </script>
    <script>
        // Filter logic
        function filterActivityTable() {
            var competitor = document.getElementById('filterCompetitor').value.trim().toLowerCase();
            var supplier = document.getElementById('filterSupplier').value.trim().toLowerCase();
            var format = document.getElementById('filterFormat').value.trim().toLowerCase();
            var market = document.getElementById('filterMarket').value.trim().toLowerCase();
            var rows = document.querySelectorAll('.activity-row');
            var competitorList = competitor ? competitor.split(',').map(function(c) {
                return c.trim();
            }).filter(Boolean) : [];
            rows.forEach(function(row) {
                var competitorVal = (row.getAttribute('data-competitor') || '').toLowerCase();
                var supplierVal = (row.getAttribute('data-supplier') || '').toLowerCase();
                var formatVal = (row.getAttribute('data-format') || '').toLowerCase();
                var marketVal = (row.getAttribute('data-market') || '').toLowerCase();
                var show = true;
                if (competitorList.length > 0 && !competitorList.some(function(c) {
                        return competitorVal.includes(c);
                    })) show = false;
                if (supplier && !supplierVal.includes(supplier)) show = false;
                if (format && !formatVal.includes(format)) show = false;
                if (market && !marketVal.includes(market)) show = false;
                row.style.display = show ? '' : 'none';
            });
        }
        ['filterCompetitor', 'filterSupplier', 'filterFormat', 'filterMarket'].forEach(function(id) {
            var el = document.getElementById(id);
            if (el) el.addEventListener('input', filterActivityTable);
        });
        // Add button
        var addBtn = document.getElementById('addActivityBtn');
        addBtn.onclick = function() {
            document.getElementById('activityModalTitle').textContent = 'Add Competitor Activity';
            document.getElementById('activityForm').reset();
            document.getElementById('activityId').value = '';
            document.getElementById('siteInfo').innerHTML = '';
            // Remove any existing image preview
            var imageCompInput = document.getElementById('imageComp');
            var imageCompDiv = imageCompInput.parentElement;
            var oldPreview = document.getElementById('currentImageCompPreview');
            if (oldPreview) oldPreview.remove();
            var modalContent = document.querySelector('#activityModal .modal-content');
            if (modalContent) modalContent.style.maxHeight = '85vh';
            new bootstrap.Modal(document.getElementById('activityModal')).show();
        };
        // Site info loader
        var siteSelect = document.getElementById('siteSelect');
        siteSelect.onchange = function() {
            var siteId = siteSelect.value;
            if (!siteId) {
                document.getElementById('siteInfo').innerHTML = '';
                return;
            }
            fetch('/ooh_project/handler/site_crud.php', {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json'
                    },
                    body: new URLSearchParams({
                        action: 'get',
                        id: siteId
                    })
                })
                .then(res => res.json())
                .then(data => {
                    // Support both {format: {...}} and {site: {...}} or direct object
                    var f = data.format || data.site || data;
                    if (!f) {
                        document.getElementById('siteInfo').innerHTML = '<div class="text-danger">Site info not found.</div>';
                        return;
                    }
                    var html = `<div class='card card-body p-2 mb-2'>
                    <div><b>Supplier:</b> ${f.supplier || ''}</div>
                    <div><b>Format:</b> ${f.format || ''}</div>
                    <div><b>Market:</b> ${f.market || ''}</div>
                    <div><b>Address:</b> ${f.street_no || ''}, ${f.street || ''}, ${f.ward || ''}, ${f.district || ''}</div>
                    <div><b>Image:</b> ${f.image_base ? `<img src='/ooh_project/media/${f.image_base}' style='max-width:120px;max-height:80px;border-radius:6px;'>` : 'No image'}</div>
                    <div><b>Current Owner:</b> ${f.current_own ? f.current_own : 'N/A'}
                        ${window.competitorNames && f.current_own && window.competitorNames.includes(f.current_own) ? '<span class="badge bg-danger ms-2">Competitor</span>' : ''}
                    </div>
                </div>`;
                    document.getElementById('siteInfo').innerHTML = html;
                });
        };
        // Edit logic
        window.openEditActivityModal = function(id) {
            fetch('/ooh_project/handler/competitor_activity_crud.php', {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json'
                    },
                    body: new URLSearchParams({
                        action: 'get',
                        id
                    })
                })
                .then(res => res.json())
                .then(data => {
                    var a = data.activity;
                    document.getElementById('activityModalTitle').textContent = 'Edit Competitor Activity';
                    document.getElementById('activityId').value = a.id;
                    document.getElementById('siteSelect').value = a.site;
                    document.getElementById('competitorSelect').value = a.competitor_id;
                    // Set airing_time if exists and valid
                    var airingInput = document.getElementById('airingTime');
                    if (a.airing_time && a.airing_time !== 'null' && a.airing_time !== '') {
                        // Try to format as YYYY-MM-DD
                        var d = new Date(a.airing_time);
                        if (!isNaN(d.getTime())) {
                            airingInput.value = d.toISOString().slice(0, 10);
                        } else {
                            airingInput.value = a.airing_time;
                        }
                    } else {
                        airingInput.value = '';
                    }
                    // Set estimate_end if exists and valid
                    var estimateInput = document.getElementById('estimateEnd');
                    if (a.estimate_end && a.estimate_end !== 'null' && a.estimate_end !== '') {
                        var e = new Date(a.estimate_end);
                        if (!isNaN(e.getTime())) {
                            estimateInput.value = e.toISOString().slice(0, 10);
                        } else {
                            estimateInput.value = a.estimate_end;
                        }
                    } else {
                        estimateInput.value = '';
                    }
                    document.getElementById('siteSelect').onchange();
                    // Set side_no if exists
                    var sideNoInput = document.getElementById('sideNo');
                    if (sideNoInput) {
                        sideNoInput.value = (typeof a.side_no !== 'undefined' && a.side_no !== null) ? a.side_no : '';
                    }
                    // Show current image if exists
                    var imageCompInput = document.getElementById('imageComp');
                    var imageCompDiv = imageCompInput.parentElement;
                    var oldPreview = document.getElementById('currentImageCompPreview');
                    if (oldPreview) oldPreview.remove();
                    if (a.image_comp) {
                        var preview = document.createElement('div');
                        preview.id = 'currentImageCompPreview';
                        preview.innerHTML = '<label class="form-label mt-2">Current image:</label><br>' +
                            '<img src="/ooh_project/media/competitor/' + encodeURIComponent(a.image_comp) + '" style="max-width:120px;max-height:80px;border-radius:6px;">';
                        imageCompDiv.insertBefore(preview, imageCompInput.nextSibling);
                    }
                    var modalContent = document.querySelector('#activityModal .modal-content');
                    if (modalContent) modalContent.style.maxHeight = '85vh';
                    new bootstrap.Modal(document.getElementById('activityModal')).show();
                });
        };
        // Delete logic
        window.deleteActivity = function(id) {
            showConfirmModal('Are you sure you want to delete this competitor activity?', function(confirmed) {
                if (!confirmed) return;
                fetch('/ooh_project/handler/competitor_activity_crud.php', {
                        method: 'POST',
                        body: new URLSearchParams({
                            action: 'delete',
                            id
                        })
                    })
                    .then(res => res.text())
                    .then(resp => {
                        location.reload();
                    });
            });
        };
        // Submit handler
        var activityForm = document.getElementById('activityForm');
        activityForm.onsubmit = function(e) {
            e.preventDefault();
            var formData = new FormData(activityForm);
            var action = formData.get('activity_id') ? 'update' : 'add';
            formData.append('action', action);
            // If estimate_end is empty, set to '' (let backend treat as NULL)
            if (!formData.get('estimate_end')) {
                formData.set('estimate_end', '');
            }
            // For add, if estimate_end is blank, remove it so backend can treat as NULL
            if (action === 'add' && (!formData.get('estimate_end') || formData.get('estimate_end') === '')) {
                formData.delete('estimate_end');
            }
            fetch('/ooh_project/handler/competitor_activity_crud.php', {
                    method: 'POST',
                    body: formData
                })
                .then(res => res.text())
                .then(resp => {
                    location.reload();
                });
        };
    </script>
    <?php include __DIR__ . '/common.php'; ?>
    <script src="/ooh_project/modules/common.js"></script>
    <script>
        // Prepare competitor names for modal site info
        window.competitorNames = [
            <?php foreach ($competitors as $c): ?> "<?= addslashes($c['name']) ?>",
            <?php endforeach; ?>
        ];
    </script>
    <!-- Active Message Modal -->
    <?php include __DIR__ . '/common.php'; ?>
    <script src="/ooh_project/modules/common.js"></script>

</body>

</html>