<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/lib/session.php';
require_auth();
$user = current_user();

$pdo = getDbConnection();

// Helpers
function n0($v) { return $v === null ? 0 : (float)$v; }
function i0($v) { return $v === null ? 0 : (int)$v; }
function fmt_money($v) { return number_format((float)$v, 0, ',', ' '); }
function fmt_qty($v) { return number_format((float)$v, 0, ',', ' '); }

// 🔹 Lecture du dernier KPI calculé
$last_kpi = $pdo->query("
    SELECT * FROM kpis ORDER BY calculated_at DESC LIMIT 1
")->fetch(PDO::FETCH_ASSOC);

$coutRotation        = $last_kpi ? (float)$last_kpi['cost_rotation'] : 0;
$seuilRentabilite    = $last_kpi ? (float)$last_kpi['breakeven_volume'] : 0;
$prixMoyenConcurrent = $last_kpi ? (float)$last_kpi['competitor_avg_price'] : 0;
$scoreFaisabilite    = $last_kpi ? (float)$last_kpi['feasibility_score'] : 0;
$dateCalcul          = $last_kpi ? date('d/m/Y H:i', strtotime($last_kpi['calculated_at'])) : '—';

// 🔹 Indicateurs "live"
$portsEnquetes = i0($pdo->query("
    SELECT COUNT(DISTINCT p.id)
    FROM ports p
    JOIN port_costs pc ON pc.port_id = p.id
")->fetchColumn());

$clientsEnquetes = i0($pdo->query("
    SELECT COUNT(DISTINCT c.id)
    FROM clients c
    JOIN demands d ON d.client_id = c.id
")->fetchColumn());

$concurrents = i0($pdo->query("SELECT COUNT(*) FROM competitors")->fetchColumn());

$totalPorts = i0($pdo->query("SELECT COUNT(*) FROM ports")->fetchColumn());
$totalClients = i0($pdo->query("SELECT COUNT(*) FROM clients")->fetchColumn());
$totalPossible = max(0, $totalPorts + $totalClients);
$avancementGlobal = $totalPossible > 0 ? round((($portsEnquetes + $clientsEnquetes) / $totalPossible) * 100) : 0;

// 🔹 Recommandations dynamiques
$reco = [];
if ($coutRotation > 0 && $prixMoyenConcurrent > 0) {
    $margeRel = ($prixMoyenConcurrent - $coutRotation) / $coutRotation;
    if ($margeRel >= 0.15) {
        $reco[] = "Marge confortable (~" . round($margeRel * 100) . "%) → Prioriser prospection.";
    } elseif ($margeRel > 0) {
        $reco[] = "Marge faible (" . round($margeRel * 100) . "%) → Négocier coûts ou optimiser OPEX.";
    } else {
        $reco[] = "Prix concurrent ≤ coût rotation → Réétudier pricing ou routes.";
    }
} else {
    $reco[] = "Saisir au moins 1 coût portuaire et 1 prix concurrent.";
}
if ($avancementGlobal < 50) $reco[] = "Accélérer les enquêtes pour fiabiliser les KPIs.";
if ($portsEnquetes === 0) $reco[] = "Aucun port avec coûts renseignés.";
if ($clientsEnquetes === 0) $reco[] = "Aucun client avec demande.";
if ($concurrents === 0) $reco[] = "Aucun concurrent saisi.";

// 🔹 Couleur badge
function badgeColor($value, $goodHigh = true, $t1 = 50, $t2 = 80) {
    $v = (float)$value;
    if (!$goodHigh) $v = 100 - $v;
    if ($v >= $t2) return '#22c55e';
    if ($v >= $t1) return '#f59e0b';
    return '#ef4444';
}

include __DIR__ . '/partials/header.php';
?>


<style>
.kpi-card {background:#1e293b; padding:15px; border-radius:8px;}
.progress-bar {background:#334155; border-radius:4px; overflow:hidden; height:8px;}
.progress-fill {height:100%; background:#38bdf8; width:0; transition:width 1.5s ease;}
</style>

<div style="padding:20px; color:white; background:#0f172a; min-height:100vh;">
    <h2 style="color:#38bdf8;">Tableau de bord</h2>
    <p>Bienvenue, <strong><?= htmlspecialchars($user['NAME']) ?></strong> 👋</p>

    <!-- KPIs -->
    <h3 style="margin-top:20px; color:#38bdf8;">KPIs en temps réel</h3>
    <?php if (!empty($_SESSION['success_message'])): ?>
        <div style="background:#16a34a; color:white; padding:10px; border-radius:4px; margin-bottom:15px;">
            <?= $_SESSION['success_message']; ?>
        </div>
        <?php unset($_SESSION['success_message']); ?>
    <?php endif; ?>

    <a href="<?= $basePath; ?>/modules/action_calcul/calc_kpis.php" 
    style="display:inline-block; padding:10px 15px; background:#38bdf8; color:#0f172a; font-weight:bold; border-radius:4px; text-decoration:none;">
    🔄 Recalculer les KPI
</a>

<?php
$last_kpi = $pdo->query("SELECT * FROM kpis ORDER BY calculated_at DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
?>

<?php if ($last_kpi): ?>
    <h3 style="color:#38bdf8; margin-top:20px;">📊 Derniers KPI calculés</h3>

    <!-- Conteneur scrollable -->
    <div style="overflow-x:auto; -webkit-overflow-scrolling:touch; border-radius:6px; margin-top:10px;">
        <table style="min-width:600px; width:100%; border-collapse:collapse; background:#0f172a;">
            <thead>
                <tr style="background:#334155; color:white;">
                    <th style="padding:8px; text-align:left;">Coût Rotation</th>
                    <th style="padding:8px; text-align:left;">Seuil Rentabilité (Volume)</th>
                    <th style="padding:8px; text-align:left;">Prix Moyen Concurrent</th>
                    <th style="padding:8px; text-align:left;">Score Faisabilité</th>
                    <th style="padding:8px; text-align:left;">Calculé le</th>
                </tr>
            </thead>
            <tbody>
                <tr style="border-bottom:1px solid #1e293b;">
                    <td style="padding:8px;"><?= number_format($last_kpi['cost_rotation'], 2, ',', ' ') ?></td>
                    <td style="padding:8px;"><?= number_format($last_kpi['breakeven_volume'], 2, ',', ' ') ?></td>
                    <td style="padding:8px;"><?= number_format($last_kpi['competitor_avg_price'], 2, ',', ' ') ?></td>
                    <td style="padding:8px;"><?= number_format($last_kpi['feasibility_score'], 2, ',', ' ') ?> / 100</td>
                    <td style="padding:8px;"><?= date('d/m/Y H:i', strtotime($last_kpi['calculated_at'])) ?></td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- Styles responsive -->
    <style>
        @media (max-width: 600px) {
            table th, table td {
                padding: 6px;
                font-size: 14px;
            }
        }
    </style>

<?php else: ?>
    <p style="color:#94a3b8; margin-top:15px;">Aucun KPI calculé pour le moment.</p>
<?php endif; ?>


    <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:15px; margin-top:15px;">
        <div class="kpi-card">
            <h4>Coût rotation estimé</h4>
            <p style="font-size:1.6rem; font-weight:bold;"><?= fmt_money($coutRotation) ?> FCFA</p>
        </div>
        <div class="kpi-card">
            <h4>Seuil rentabilité</h4>
            <p style="font-size:1.6rem; font-weight:bold;"><?= fmt_qty($seuilRentabilite) ?> tonnes</p>
        </div>
        <div class="kpi-card">
            <h4>Prix moyen concurrent</h4>
            <p style="font-size:1.6rem; font-weight:bold;"><?= fmt_money($prixMoyenConcurrent) ?> FCFA/t</p>
        </div>
        <div class="kpi-card">
            <h4>Score faisabilité</h4>
            <?php $colorF = badgeColor($scoreFaisabilite, true); ?>
            <p style="font-size:1.6rem; font-weight:bold; color:<?= $colorF ?>;"><?= $scoreFaisabilite ?>/100</p>
        </div>
    </div>

    <!-- Recommandations -->
    <h3 style="margin-top:30px; color:#38bdf8;">Prochaines actions</h3>
    <div class="kpi-card" style="margin-bottom:20px;">
        <ul>
            <?php foreach ($reco as $r): ?>
                <li><?= htmlspecialchars($r) ?></li>
            <?php endforeach; ?>
        </ul>
    </div>

    <!-- Suivi -->
    <h3 style="color:#38bdf8;">Suivi d’avancement</h3>
    <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:15px;">
        <div class="kpi-card" style="text-align:center;">
            <h4>Ports enquêtés</h4>
            <p style="font-size:2rem; font-weight:bold;"><?= $portsEnquetes ?></p>
            <div class="progress-bar"><div class="progress-fill" style="width:<?= $totalPorts>0?($portsEnquetes/$totalPorts*100):0 ?>%"></div></div>
        </div>
        <div class="kpi-card" style="text-align:center;">
            <h4>Clients enquêtés</h4>
            <p style="font-size:2rem; font-weight:bold;"><?= $clientsEnquetes ?></p>
            <div class="progress-bar"><div class="progress-fill" style="width:<?= $totalClients>0?($clientsEnquetes/$totalClients*100):0 ?>%"></div></div>
        </div>
        <div class="kpi-card" style="text-align:center;">
            <h4>Concurrents</h4>
            <p style="font-size:2rem; font-weight:bold;"><?= $concurrents ?></p>
        </div>
        <div class="kpi-card" style="text-align:center;">
            <h4>Avancement global</h4>
            <?php $colorA = badgeColor($avancementGlobal, true); ?>
            <p style="font-size:2rem; font-weight:bold; color:<?= $colorA ?>;"><?= $avancementGlobal ?>%</p>
            <div class="progress-bar"><div class="progress-fill" style="width:<?= $avancementGlobal ?>%"></div></div>
        </div>
    </div>
    <!-- Modules -->
    <h3 style="margin-top:30px; color:#38bdf8;">Modules</h3>
    <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:15px; margin-top:15px;">
        <a href="<?= $basePath; ?>/modules/ports" class="kpi-card" style="color:#38bdf8; text-decoration:none;">📍 Fiche port</a>
        <a href="<?= $basePath; ?>/modules/clients" class="kpi-card" style="color:#38bdf8; text-decoration:none;">👥 Client & Demande</a>
        <a href="<?= $basePath; ?>/modules/competitors" class="kpi-card" style="color:#38bdf8; text-decoration:none;">📊 Concurrence</a>
        <a href="<?= $basePath; ?>/modules/opex" class="kpi-card" style="color:#38bdf8; text-decoration:none;">⚙️ OPEX navire</a>
        <a href="<?= $basePath; ?>/modules/regulations" class="kpi-card" style="color:#38bdf8; text-decoration:none;">📜 Réglementaire</a>
        <a href="<?= $basePath; ?>/modules/pilot_journal" class="kpi-card" style="color:#38bdf8; text-decoration:none;">📝 Journal pilote</a>
    </div>
    <!-- Export CSV -->
    <h3 style="margin-top:30px; color:#38bdf8;">Export des KPIs</h3>
    <form method="post" action="<?= $basePath; ?>/modules/export_kpis.php">
        <button type="submit" style="padding:10px 15px; background:#38bdf8; color:#0f172a; border:none; border-radius:5px; font-weight:bold; cursor:pointer;">
            📤 Exporter en CSV
        </button>
    </form>
    <!-- Export PDF -->
    <form method="post" action="<?= $basePath; ?>/modules/export_kpis_pdf.php" style="margin-top:10px;">
        <button type="submit" style="padding:10px 15px; background:#f87171; color:white; border:none; border-radius:5px; font-weight:bold; cursor:pointer;">
            📄 Exporter en PDF
        </button>
    </form>
</div>
<script>
// Animation des barres d’avancement
document.addEventListener("DOMContentLoaded", function() {
    document.querySelectorAll('.progress-fill').forEach(function(bar) {
        let width = bar.style.width;
        bar.style.width = '0';
        setTimeout(() => { bar.style.width = width; }, 200);
    });
});
</script>
<?php include __DIR__ . '/partials/footer.php'; ?>
