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

// Fetch Unilever brands
$unilever_brands = [];
$stmt = $pdo->query("SELECT name FROM unilever");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $unilever_brands[] = $row['name'];
}
// Fetch competitor brands
$competitor_brands = [];
$stmt = $pdo->query("SELECT name FROM competitors");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $competitor_brands[] = $row['name'];
}
// Fetch markets
$markets = [];
$stmt = $pdo->query("SELECT name FROM market");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $markets[] = $row['name'];
}
// Fetch all sites
$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;
    $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;
    }
}

// Helper: Is Unilever brand?
function is_unilever($brand, $unilever_brands) {
    return in_array(mb_strtolower($brand), array_map('mb_strtolower', $unilever_brands));
}

// Build province stats for map coloring
$provinceStats = [];
foreach ($sites as $site) {
    $prov = $site['province'] ?? '';
    $brands = preg_split('/[,;]+/', $site['current_own']);
    $hasUnilever = false; $hasCompetitor = false;
    foreach ($brands as $brand) {
        $brand = trim($brand);
        if (in_array($brand, $unilever_brands)) $hasUnilever = true;
        if (in_array($brand, $competitor_brands)) $hasCompetitor = true;
    }
    if (!isset($provinceStats[$prov])) $provinceStats[$prov] = ['unilever'=>0, 'competitor'=>0];
    if ($hasUnilever) $provinceStats[$prov]['unilever']++;
    if ($hasCompetitor) $provinceStats[$prov]['competitor']++;
}
?>
<!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: 600px; border-radius: 1rem; }
        .leaflet-popup-content img { max-width: 120px; border-radius: 0.5rem; }
        .modal-xl { max-width: 90vw; }
        .competitor-card.selected { border: 2px solid #007bff; box-shadow: 0 0 0 2px #007bff33; }
        .format-badge { font-size: 0.95em; margin-right: 0.3em; }
        #competitor-map { background: #222; }
    </style>
</head>
<body>
<div class="container-fluid py-3">
  <h2 class="mb-4 text-center text-primary">Competitor Review</h2>
  <div class="row">
    <!-- Left: col-8 -->
    <div class="col-12 col-md-8">
      <div class="row">
        <?php
        $brands = array_keys($competitors);
        $half = ceil(count($brands)/2);
        $columns = [array_slice($brands, 0, $half), array_slice($brands, $half)];
        foreach ($columns as $colBrands): ?>
          <div class="col-12 col-md-6">
            <?php foreach ($colBrands as $brand):
              $brandSites = $competitors[$brand];
              // Format breakdown
              $formats = [];
              foreach ($brandSites as $site) {
                $fmt = $site['format'] ?? 'Unknown';
                $formats[$fmt] = ($formats[$fmt] ?? 0) + 1;
              }
              ?>
              <div class="card mb-3 shadow-sm competitor-card" data-brand="<?= htmlspecialchars($brand) ?>">
                <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>
                  <div class="mb-1"><strong>Formats:</strong>
                    <?php foreach ($formats as $fmt => $qty): ?>
                      <span class="badge bg-secondary format-badge"><?= htmlspecialchars($fmt) ?>: <?= $qty ?></span>
                    <?php endforeach; ?>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endforeach; ?>
      </div>
      <!-- Charts Row -->
      <div class="row mt-4">
        <div class="col-12 col-md-6">
          <canvas id="marketShareChart"></canvas>
        </div>
        <div class="col-12 col-md-6">
          <canvas id="marketBarChart"></canvas>
        </div>
      </div>
    </div>
    <!-- Right: Map (col-4) -->
    <div class="col-12 col-md-4">
      <div id="competitor-map"></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>
// --- Data ---
const competitorSites = <?= json_encode($competitors) ?>;
const unileverBrands = <?= json_encode($unilever_brands) ?>;
const competitorBrands = <?= json_encode($competitor_brands) ?>;
const markets = <?= json_encode($markets) ?>;
const provinceStats = <?= json_encode($provinceStats) ?>;
let selectedBrand = null;

// --- Map ---
let map = L.map('competitor-map', { zoomControl: false, attributionControl: false }).setView([16.047079, 108.206230], 6);

// Vietnam GeoJSON (use your own file or CDN, here is a placeholder)
fetch('/ooh_project/modules/json/vietnam-provinces.geojson')
.then(res => res.json())
.then(vnGeoJson => {
    function getProvinceColor(u, c) {
        if (u && c) return '#ff9900'; // orange
        if (u) return `rgba(0,123,255,${Math.min(0.3 + u/10, 1)})`; // blue
        if (c) return `rgba(220,53,69,${Math.min(0.3 + c/10, 1)})`; // red
        return '#cccccc'; // gray
    }
    function updateMap(brand = null) {
        map.eachLayer(l => { if (l instanceof L.GeoJSON || l instanceof L.Path) map.removeLayer(l); });
        let stats = {};
        if (brand) {
            // Only show provinces where this brand is present
            Object.keys(competitorSites[brand] || {}).forEach(i => {
                let site = competitorSites[brand][i];
                let prov = site.province || '';
                let isUni = unileverBrands.map(b => b.toLowerCase()).includes(brand.toLowerCase());
                let isComp = competitorBrands.map(b => b.toLowerCase()).includes(brand.toLowerCase());
                if (!stats[prov]) stats[prov] = {unilever:0, competitor:0};
                if (isUni) stats[prov].unilever++;
                if (isComp) stats[prov].competitor++;
            });
        } else {
            stats = provinceStats;
        }
        L.geoJson(vnGeoJson, {
            style: function(feature) {
                const prov = feature.properties.NAME_1;
                const u = stats[prov]?.unilever || 0;
                const c = stats[prov]?.competitor || 0;
                return {
                    fillColor: getProvinceColor(u, c),
                    weight: 1,
                    color: '#333',
                    fillOpacity: 0.85
                };
            }
        }).addTo(map);
    }
    updateMap();
    // Card click handler
    document.querySelectorAll('.competitor-card').forEach(card => {
        card.addEventListener('click', function() {
            document.querySelectorAll('.competitor-card').forEach(c => c.classList.remove('selected'));
            this.classList.add('selected');
            selectedBrand = this.dataset.brand;
            updateMap(selectedBrand);
            showBrandGallery(selectedBrand);
        });
    });
});

// --- Gallery Modal ---
function showBrandGallery(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">
                  <strong>Market:</strong> ${site.market || ''}<br>
                  <strong>Location:</strong> ${site.street || ''}, ${site.district || ''}<br>
                  <strong>Size:</strong> ${site.size_meter ? site.size_meter + 'm' : (site.size_pixel ? site.size_pixel + 'px' : '')}
                </div>
            </div>`;
            count++;
        }
    });
    document.getElementById('galleryTitle').textContent = brand + ' - Gallery (' + count + ' images)';
    new bootstrap.Modal(document.getElementById('galleryModal')).show();
}

// --- Market Share Pie Chart (Unilever vs. Others) ---
const marketData = (() => {
    let unileverCount = 0, compCount = 0;
    Object.entries(competitorSites).forEach(([brand, sites]) => {
        if (unileverBrands.map(b => b.toLowerCase()).includes(brand.toLowerCase())) unileverCount += sites.length;
        else compCount += sites.length;
    });
    return [
        {label: 'Unilever', count: unileverCount},
        {label: 'Competitors', count: compCount}
    ];
})();
new Chart(document.getElementById('marketShareChart').getContext('2d'), {
    type: 'pie',
    data: {
        labels: marketData.map(d => d.label),
        datasets: [{
            data: marketData.map(d => d.count),
            backgroundColor: ['#007bff', '#dc3545']
        }]
    },
    options: { plugins: { legend: { display: true, position: 'bottom' } } }
});

// --- Market Bar Chart (by market, % by competitor) ---
const barLabels = markets;
const barData = [];
Object.entries(competitorSites).forEach(([brand, sites]) => {
    let arr = [];
    barLabels.forEach(market => {
        let total = sites.filter(s => (s.market || '').toLowerCase() === market.toLowerCase()).length;
        arr.push(total);
    });
    barData.push({label: brand, data: arr});
});
new Chart(document.getElementById('marketBarChart').getContext('2d'), {
    type: 'bar',
    data: {
        labels: barLabels,
        datasets: barData.map((d, i) => ({
            label: d.label,
            data: d.data,
            backgroundColor: unileverBrands.map(b => b.toLowerCase()).includes(d.label.toLowerCase()) ? '#007bff' : '#dc3545',
            stack: 'Stack 0'
        }))
    },
    options: {
        plugins: { legend: { display: true, position: 'bottom' } },
        responsive: true,
        scales: { x: { stacked: true }, y: { stacked: true, beginAtZero: true } }
    }
});
</script>
</body>
</html>