<?php
// filepath: c:\Users\ASUS PN40\CDrive\xampp\business\ooh_project\modules\competitor_review.php
require_once __DIR__ . '/navbar.php';
if (session_status() === PHP_SESSION_NONE) session_start();
$pdo = require __DIR__ . '/../config/db.php';
$role = $_SESSION['role'] ?? 'other';

// Fetch all sites with competitor info
$sites = $pdo->query('SELECT * FROM sites')->fetchAll(PDO::FETCH_ASSOC);

// Build competitor => [sites] mapping, supporting multiple competitors per site
$competitors = [];
foreach ($sites as $site) {
    if (empty($site['current_own'])) continue;
    // Support multiple competitors per site (comma or semicolon separated)
    $brands = preg_split('/[,;]+/', $site['current_own']);
    foreach ($brands as $brand) {
        $brand = trim($brand);
        if (!$brand) continue;
        if (!isset($competitors[$brand])) $competitors[$brand] = [];
        $competitors[$brand][] = $site;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Competitor Review</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap & Leaflet & Chart.js -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { background: #f8f9fa; }
        .card-title { font-size: 1.2em; }
        .gallery-img { object-fit: cover; width: 100%; height: 140px; border-radius: 0.5rem; }
        #competitor-map { height: 500px; border-radius: 1rem; }
        .leaflet-popup-content img { max-width: 120px; border-radius: 0.5rem; }
        .modal-xl { max-width: 90vw; }
    </style>
</head>
<body>
<div class="container-fluid py-3">
    <h2 class="mb-4 text-center text-primary">Competitor Review</h2>

    <!-- Competitor Summary Cards -->
    <div class="row g-3 mb-4">
    <?php foreach ($competitors as $brand => $brandSites): ?>
      <div class="col-12 col-md-4 col-lg-3">
        <div class="card shadow-sm h-100">
          <div class="card-body">
            <h5 class="card-title"><?= htmlspecialchars($brand) ?></h5>
            <p class="mb-1"><strong>Sites:</strong> <?= count($brandSites) ?></p>
            <p class="mb-1"><strong>Markets:</strong> 
                <?= htmlspecialchars(implode(', ', array_unique(array_filter(array_map(fn($s) => $s['market'] ?? '', $brandSites))))) ?>
            </p>
            <button class="btn btn-sm btn-outline-primary view-map-btn" data-brand="<?= htmlspecialchars($brand) ?>">View on Map</button>
            <button class="btn btn-sm btn-outline-secondary view-gallery-btn" data-brand="<?= htmlspecialchars($brand) ?>">Gallery</button>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
    </div>

    <!-- Map Section -->
    <div class="row mb-4">
      <div class="col-12">
        <div id="competitor-map"></div>
      </div>
    </div>

    <!-- Market Share Chart -->
    <div class="row mb-4">
      <div class="col-12 col-md-8 mx-auto">
        <div class="card card-body shadow-sm">
          <h5 class="mb-3 text-center">Market Share by Site Count</h5>
          <canvas id="marketShareChart" height="120"></canvas>
        </div>
      </div>
    </div>

    <!-- Gallery Modal -->
    <div class="modal fade" id="galleryModal" tabindex="-1">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="galleryTitle"></h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <div class="row" id="galleryImages"></div>
          </div>
        </div>
      </div>
    </div>
</div>

<script>
const competitorSites = <?= json_encode($competitors) ?>;

// --- Map ---
let map = L.map('competitor-map').setView([10.762622, 106.660172], 11); // Center on HCM
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; OpenStreetMap contributors'
}).addTo(map);

let markers = [];
function showCompetitorOnMap(brand) {
    // Remove old markers
    markers.forEach(m => map.removeLayer(m));
    markers = [];
    let sites = competitorSites[brand];
    if (!sites) return;
    let bounds = [];
    sites.forEach(site => {
        if (!site.lat || !site.lng) return;
        let marker = L.marker([site.lat, site.lng]).addTo(map)
            .bindPopup(`<strong>${brand}</strong><br>${site.location || ''}<br>
                ${site.image_comp ? `<img src="../media/${site.image_comp}" style='max-width:120px;'>` : ''}`);
        markers.push(marker);
        bounds.push([site.lat, site.lng]);
    });
    if (bounds.length) {
        map.fitBounds(bounds, {padding: [30,30]});
    }
}

// Button handlers for map
document.querySelectorAll('.view-map-btn').forEach(btn => {
    btn.addEventListener('click', e => {
        showCompetitorOnMap(btn.dataset.brand);
        window.scrollTo({top: document.getElementById('competitor-map').offsetTop - 80, behavior: 'smooth'});
    });
});

// --- Gallery ---
function showGallery(brand) {
    const sites = competitorSites[brand];
    const gallery = document.getElementById('galleryImages');
    gallery.innerHTML = '';
    let count = 0;
    sites.forEach(site => {
        if (site.image_comp) {
            gallery.innerHTML += `<div class="col-6 col-md-4 col-lg-3 mb-3">
                <img src="../media/${site.image_comp}" class="gallery-img shadow-sm" title="${site.location || ''}">
                <div class="small text-muted mt-1">${site.location || ''}</div>
            </div>`;
            count++;
        }
    });
    document.getElementById('galleryTitle').textContent = brand + ' - Gallery (' + count + ' images)';
    new bootstrap.Modal(document.getElementById('galleryModal')).show();
}
document.querySelectorAll('.view-gallery-btn').forEach(btn => {
    btn.addEventListener('click', e => {
        showGallery(btn.dataset.brand);
    });
});

// --- Market Share Chart ---
const marketData = Object.entries(competitorSites).map(([brand, sites]) => ({
    brand, count: sites.length
}));
const ctx = document.getElementById('marketShareChart').getContext('2d');
new Chart(ctx, {
    type: 'pie',
    data: {
        labels: marketData.map(d => d.brand),
        datasets: [{
            data: marketData.map(d => d.count),
            backgroundColor: [
                '#007bff','#28a745','#ffc107','#dc3545','#6f42c1','#20c997','#fd7e14','#17a2b8',
                '#ff6384','#36a2eb','#cc65fe','#ffce56','#8bc34a','#e91e63','#00bcd4','#ff9800'
            ]
        }]
    },
    options: {
        plugins: {
            legend: { display: true, position: 'bottom' }
        }
    }
});
</script>
</body>
</html>