<?php
session_start();

// Activation de l'affichage des erreurs pour le débogage (à retirer en production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

/**
 * CONNEXION À LA BASE DE DONNÉES
 */
try {
    $bd = new PDO('mysql:host=localhost;dbname=referendi_appli-microtiq', 'appli', 'Referendi-*/@84320!');
    $bd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    die('<div class="bg-red-900/30 text-red-400 p-4 rounded-xl border border-red-800 max-w-md text-center mx-auto mt-20 font-medium shadow-sm">Erreur de connexion : '.$e->getMessage().'</div>');
}

/**
 * RÉCUPÉRATION DE L'ID ET DU MOT DE PASSE DEPUIS L'URL
 */
$error = null;
$id = null;
$mdp_attendu = null;
$is_authenticated = false;

if ((isset($_GET['suivi']) && !empty($_GET['suivi']))|| (isset($_POST['suivi']) && !empty($_POST['suivi']))){
    $suivi_recup = isset($_GET['suivi']) ? $_GET['suivi'] : $_POST['suivi'];
    $suivi_param = base64_decode($suivi_recup);
    if ($suivi_param) {
        $parts = explode('_', $suivi_param);
        if (count($parts) >= 2) {
            $id = $parts[0];
            $mdp_attendu = $parts[1]; 
        } else {
            $error = "Le format du lien de suivi est incomplet.";
        }
    } else {
        $error = "Le lien de suivi est invalide.";
    }
} else {
    $error = "Aucun identifiant de suivi n'a été détecté.";
}

/**
 * TRAITEMENT DU FORMULAIRE DE CONNEXION (POST)
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mdp_client']) && $id) {
    $mdp_saisi = $_POST['mdp_client'];
    if ($mdp_saisi === $mdp_attendu) {
        $_SESSION['auth_suivi_' . $id] = true;
        $error = null;
    } else {
        $error = "Le code saisi est incorrect.";
    }
}

/**
 * VÉRIFICATION DE L'AUTHENTIFICATION EN SESSION
 */
if ($id && isset($_SESSION['auth_suivi_' . $id]) && $_SESSION['auth_suivi_' . $id] === true) {
    $is_authenticated = true;
}

/**
 * RÉCUPÉRATION DES DONNÉES SI AUTHENTIFIÉ
 */
$data = null;
$devis = null;
$total_ttc_calcule = 0;
$facture_finale = 0;
$etat_val = 0; 
$fin_timestamp = 0;
$agence = "Non spécifiée";

if ($is_authenticated && $id) {
    try {
        // 1. Récupération de la fiche atelier avec le champ facture
        $stmt = $bd->prepare("SELECT client, materiel, descriptif, chantier, entree, fin, avance, delai, montant, etat, agence, facture FROM microtiq_entree_atelier WHERE id = :id LIMIT 1");
        $stmt->execute(['id' => $id]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$data) {
            $error = "Dossier introuvable dans la base de données.";
            $is_authenticated = false;
        } else {
            // Récupération de l'état, de la date de fin, agence et facture
            $fin_timestamp = (!empty($data['fin']) && is_numeric($data['fin'])) ? (int)$data['fin'] : 0;
            
            // Si une date de fin existe, l'état passe obligatoirement à 2 (Terminé)
            if ($fin_timestamp > 0) {
                $etat_val = 2;
            } else {
                $etat_val = isset($data['etat']) ? (int)$data['etat'] : 0;
            }
            
            $agence = !empty($data['agence']) ? htmlspecialchars($data['agence']) : 'Non spécifiée';
            $facture_finale = (!empty($data['facture'])) ? (float)str_replace(',', '.', (string)$data['facture']) : 0;

            // 2. Récupération du devis
            $stmtDevis = $bd->prepare("SELECT id, date, corps FROM microtiq_devis WHERE idfiche = :id ORDER BY id DESC LIMIT 1");
            $stmtDevis->execute(['id' => $id]);
            $devis = $stmtDevis->fetch(PDO::FETCH_ASSOC);

            // 3. Calcul du Total
            if ($devis && !empty($devis['corps'])) {
                $lignes = json_decode($devis['corps'], true);
                if (json_last_error() !== JSON_ERROR_NONE || !is_array($lignes)) {
                    $lignes = @unserialize($devis['corps']);
                }
                $total_calcule = 0;
                if (is_array($lignes)) {
                    foreach ($lignes as $ligne) {
                        if (is_array($ligne)) {
                            $pu = isset($ligne['pu']) ? $ligne['pu'] : (isset($ligne['prix']) ? $ligne['prix'] : 0);
                            $pu = (float)str_replace(',', '.', (string)$pu);
                            $qte = isset($ligne['qte']) ? $ligne['qte'] : (isset($ligne['quantite']) ? $ligne['quantite'] : 1);
                            $qte = (float)str_replace(',', '.', (string)$qte);
                            $total_calcule += ($pu * $qte);
                        }
                    }
                    $total_ttc_calcule = $total_calcule;
                }
            }
            if ($total_ttc_calcule <= 0 && !empty($data['montant'])) {
                $total_ttc_calcule = (float)str_replace(',', '.', (string)$data['montant']);
            }
        }
    } catch (Exception $e) {
        $error = "Erreur lors de la lecture : " . $e->getMessage();
        $is_authenticated = false;
    }
}

// Configuration des 3 états possibles pour la barre de progression
$etats_suivi = [
    0 => [
        'icon' => 'bi-hourglass-split', 
        'label_short' => 'En attente', 
        'label_long' => 'En attente', 
        'active_cls' => 'bg-gradient-to-br from-slate-600 to-slate-700 text-white border-slate-400 shadow-[0_0_15px_rgba(148,163,184,0.4)] ring-2 ring-slate-400 transform scale-[1.05] z-10', 
        'inactive_cls' => 'bg-slate-800/50 text-slate-500 border-slate-700 opacity-60 grayscale'
    ],
    1 => [
        'icon' => 'bi-tools', 
        'label_short' => 'En cours', 
        'label_long' => 'En cours', 
        'active_cls' => 'bg-gradient-to-br from-blue-500 to-blue-700 text-white border-blue-300 shadow-[0_0_20px_rgba(59,130,246,0.6)] ring-2 ring-blue-400 transform scale-[1.05] z-10', 
        'inactive_cls' => 'bg-slate-800/50 text-slate-500 border-slate-700 opacity-60 grayscale'
    ],
    2 => [
        'icon' => 'bi-check-circle-fill', 
        'label_short' => 'Terminé', 
        'label_long' => 'Terminé', 
        'active_cls' => 'bg-gradient-to-br from-emerald-500 to-emerald-700 text-white border-emerald-300 shadow-[0_0_20px_rgba(16,185,129,0.6)] ring-2 ring-emerald-400 transform scale-[1.05] z-10', 
        'inactive_cls' => 'bg-slate-800/50 text-slate-500 border-slate-700 opacity-60 grayscale'
    ]
];

if ($fin_timestamp > 0) {
    $etats_suivi[2]['label_long'] = 'Terminé le ' . date('d/m/Y', $fin_timestamp);
    $etats_suivi[2]['label_short'] = 'Le ' . date('d/m/y', $fin_timestamp);
}
?>
<!DOCTYPE html>
<html lang="fr" class="scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Suivi Atelier - Microtiq</title>
    
    <link rel="shortcut icon" href="https://shop.microtiq.com/favicon.ico" type="image/x-icon">
    <link rel="icon" href="https://shop.microtiq.com/favicon.ico" type="image/x-icon">
    <link rel="apple-touch-icon" href="https://shop.microtiq.com/apple-touch-icon.png">

    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <script src="https://unpkg.com/lucide@latest"></script>

    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
        
        /* Ajustement du body pour cohabiter avec Tailwind */
        body { font-family: 'Inter', sans-serif; background-color: #020617; overflow-y: auto; color: #e2e8f0; }
        
        /* Animations douces */
        .fade-in-up { animation: fadeInUp 0.5s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(15px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Arrière-plan vivant (Glows mouvants) */
        @keyframes float1 { 0%, 100% { transform: translate(0, 0) scale(1); } 50% { transform: translate(-20px, 15px) scale(1.05); } }
        @keyframes float2 { 0%, 100% { transform: translate(0, 0) scale(1); } 50% { transform: translate(20px, -15px) scale(1.05); } }
        @keyframes float3 { 0%, 100% { transform: translate(0, 0) scale(1); } 50% { transform: translate(-15px, -20px) scale(1.05); } }
        
        .ambient-glow-1 { animation: float1 12s ease-in-out infinite; }
        .ambient-glow-2 { animation: float2 15s ease-in-out infinite; }
        .ambient-glow-3 { animation: float3 10s ease-in-out infinite; }

        /* Personnalisation de la barre de défilement */
        .custom-scroll::-webkit-scrollbar { width: 6px; }
        .custom-scroll::-webkit-scrollbar-track { background: transparent; }
        .custom-scroll::-webkit-scrollbar-thumb { background: #334155; border-radius: 10px; }
        .custom-scroll::-webkit-scrollbar-thumb:hover { background: #475569; }

        /* Styles d'impression */
        @media print {
            body { background: white !important; color: black !important; }
            .print-hide, .ambient-glow, nav, footer { display: none !important; }
            .shadow-sm, .shadow, .shadow-md, .shadow-lg, .shadow-xl { box-shadow: none !important; }
            .backdrop-blur-xl { backdrop-filter: none !important; background: white !important; }
            .border-slate-700, .border-white\/60 { border-color: #e2e8f0 !important; }
            * { color: black !important; }
        }
    </style>
</head>
<body class="min-h-screen flex flex-col font-sans antialiased overflow-x-hidden relative z-0">

    <nav class="fixed top-0 w-full z-50 bg-[#0a0f1c]/80 backdrop-blur-xl border-b border-white/5 font-bold print-hide">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-20 items-center">
                <a href="/" class="flex-shrink-0 flex items-center gap-3 group transition-transform hover:scale-105">
                    <span class="text-2xl font-black tracking-tight text-white uppercase">
                        MICRO<span class="text-blue-500">TIQ</span>
                    </span>
                    <span class="hidden sm:inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-blue-500/10 text-blue-400 border border-blue-500/20 uppercase tracking-widest">
                        Particuliers
                    </span>
                </a>
                
                <div class="hidden md:flex space-x-8 items-center text-sm font-bold">
                    <a href="/particulier/index.html" class="text-slate-300 hover:text-white transition-colors">Accueil</a>
                    <a href="/particulier/services.html" class="text-slate-300 hover:text-white transition-colors">Nos Expertises</a>
                    <a href="/particulier/tarifs.html" class="text-slate-300 hover:text-white transition-colors">Tarifs</a>
                    <a href="/particulier/support.html" class="text-white border-b-2 border-blue-500 transition-colors">Support</a>
                    <a href="/particulier/contact.html" class="px-6 py-2.5 text-white bg-blue-600 rounded-full hover:bg-blue-500 transition-all shadow-lg shadow-blue-600/30 uppercase text-xs tracking-tighter">
                        Contactez-nous
                    </a>
                </div>

                <div class="md:hidden flex items-center">
                    <button id="mobile-menu-btn" class="text-slate-300 hover:text-white p-2">
                        <i data-lucide="menu" class="w-6 h-6" id="menu-icon"></i>
                        <i data-lucide="x" class="w-6 h-6 hidden" id="close-icon"></i>
                    </button>
                </div>
            </div>
        </div>

        <div id="mobile-menu" class="md:hidden fixed top-20 left-0 w-full bg-[#0a0f1c]/95 backdrop-blur-xl border-b border-white/5 transition-all duration-300 ease-in-out opacity-0 invisible h-0 overflow-hidden z-40">
            <div class="px-4 py-6 space-y-4">
                <a href="index.html" class="block text-lg font-medium text-slate-300 mobile-link">Accueil</a>
                <a href="services.html" class="block text-lg font-medium text-slate-300 mobile-link">Nos Expertises</a>
                <a href="tarifs.html" class="block text-lg font-medium text-slate-300 mobile-link">Tarifs</a>
                <a href="support.html" class="block text-lg font-medium text-white mobile-link">Support</a>
                <a href="contact.html" class="block mt-6 px-5 py-3 text-center font-medium text-white bg-blue-600 rounded-xl mobile-link">
                    Contactez-nous
                </a>
            </div>
        </div>
    </nav>


    <main class="flex-grow flex flex-col items-center justify-center p-4 pt-32 pb-16 relative w-full z-0">
        
        <div class="absolute inset-0 overflow-hidden pointer-events-none -z-10 ambient-glow">
            <div class="ambient-glow-1 absolute top-[10%] left-[10%] w-[50vw] h-[50vw] rounded-full bg-blue-500/15 blur-[100px]"></div>
            <div class="ambient-glow-2 absolute top-[20%] right-[10%] w-[40vw] h-[40vw] rounded-full bg-indigo-500/15 blur-[100px]"></div>
            <div class="ambient-glow-3 absolute bottom-[10%] left-[20%] w-[40vw] h-[40vw] rounded-full bg-emerald-500/15 blur-[100px]"></div>
        </div>

        <?php if ($error && !$id): ?>
            <div class="max-w-md w-full bg-slate-900/95 backdrop-blur-xl p-6 rounded-2xl shadow-xl border border-slate-700/60 text-center fade-in-up">
                <div class="w-12 h-12 bg-gradient-to-br from-red-900/50 to-red-800/30 text-red-500 rounded-full flex items-center justify-center mx-auto mb-4 border border-red-800/50 shadow-sm">
                    <i class="bi bi-shield-exclamation text-xl"></i>
                </div>
                <h2 class="text-lg font-bold text-white mb-2">Lien Invalide</h2>
                <p class="text-slate-400 text-sm"><?php echo htmlspecialchars($error); ?></p>
            </div>

        <?php elseif (!$is_authenticated): ?>
            <div class="max-w-md w-full bg-slate-900/95 backdrop-blur-xl p-6 md:p-8 rounded-3xl shadow-xl shadow-black/50 border border-slate-700/60 fade-in-up relative overflow-hidden">
                <div class="absolute top-0 left-0 w-full h-1.5 bg-gradient-to-r from-blue-500 via-indigo-500 to-emerald-400"></div>
                <div class="text-center mb-6 mt-2">
                    <div class="w-14 h-14 bg-gradient-to-br from-slate-800 to-slate-900 text-slate-200 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-black/40 border border-slate-700">
                        <i class="bi bi-lock-fill text-xl"></i>
                    </div>
                    <h1 class="text-2xl font-black text-white tracking-tight">Accès au Suivi</h1>
                    <p class="text-slate-400 text-sm mt-1">Dossier de réparation <span class="font-bold text-slate-200">#<?php echo htmlspecialchars($id); ?></span></p>
                </div>

                <form method="POST" class="space-y-4">
                    <div>
                        <label for="mdp_client" class="block text-xs font-bold uppercase text-slate-500 tracking-wider mb-1.5 text-center">Code de sécurité</label>
                        <input type="password" name="mdp_client" id="mdp_client" required autofocus
                               class="w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-xl text-center text-xl font-mono tracking-[0.5em] text-white focus:bg-slate-800 focus:border-blue-500 focus:ring-4 focus:ring-blue-500/20 transition-all outline-none shadow-inner"
                               placeholder="••••">
                    </div>

                    <?php if ($error): ?>
                        <div class="p-2.5 bg-red-900/30 text-red-400 text-xs font-bold rounded-xl text-center border border-red-800/50 flex items-center justify-center gap-1.5 shadow-sm">
                            <i class="bi bi-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?>
                        </div>
                    <?php endif; ?>

                    <button type="submit" class="w-full py-3 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 text-white rounded-xl font-bold transition-all shadow-lg shadow-blue-900/50 flex items-center justify-center gap-2 text-sm border border-blue-500/50">
                        <span>Accéder au dossier</span>
                        <i class="bi bi-arrow-right"></i>
                    </button>
                </form>

                <p class="mt-5 text-center text-xs text-slate-500 font-medium">
                    Votre code secret figure sur votre fiche.
                </p>
            </div>

        <?php else: ?>
            <div class="max-w-4xl w-full bg-slate-900/95 backdrop-blur-xl rounded-2xl shadow-2xl shadow-black/60 border border-slate-700/60 overflow-hidden fade-in-up relative flex flex-col max-h-[96vh]">
                
                <div class="absolute top-0 left-0 w-full h-1.5 bg-gradient-to-r from-blue-500 via-indigo-500 to-emerald-400 z-20"></div>

                <div class="bg-gradient-to-b from-slate-900 to-slate-800/50 px-5 md:px-6 pt-5 pb-3 border-b border-slate-800 flex-shrink-0 z-10">
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-3">
                        <div>
                            <div class="flex flex-wrap items-center gap-2 mb-1">
                                <div class="inline-flex items-center gap-1.5 px-2 py-0.5 bg-gradient-to-r from-slate-800 to-slate-700 text-slate-300 border border-slate-600 rounded text-[9px] font-bold tracking-widest uppercase shadow-sm">
                                    <i class="bi bi-cpu text-slate-400"></i> Dossier Atelier
                                </div>
                            </div>
                            <h1 class="text-xl md:text-2xl font-black text-white tracking-tight mt-0.5">Suivi d'intervention <span class="text-slate-500 font-medium text-base ml-1">#<?php echo htmlspecialchars($id); ?></span></h1>
                            <div class="flex items-center gap-1.5 mt-1 text-xs font-bold text-slate-400 bg-slate-800/80 inline-flex px-2 py-0.5 rounded border border-slate-700/60">
                                <i class="bi bi-geo-alt-fill text-indigo-400"></i> Agence de <span class="text-slate-300 uppercase tracking-wide"><?php echo $agence; ?></span>
                            </div>
                        </div>
                        
                        <div class="text-left md:text-right w-full md:w-auto mt-2 md:mt-0">
                            <span class="text-[9px] text-slate-500 uppercase font-bold tracking-widest block mb-0.5">Dépôt le</span>
                            <span class="font-bold text-sm text-slate-200 bg-slate-800 px-2.5 py-1 rounded-md border border-slate-700 shadow-sm inline-block">
                                <?php echo is_numeric($data['entree']) ? date('d/m/Y', $data['entree']) : htmlspecialchars($data['entree']); ?>
                            </span>
                        </div>
                    </div>

                    <div class="flex items-center justify-between gap-1.5 sm:gap-2 mt-4 pt-4 border-t border-slate-700/60 w-full">
                        <?php foreach ($etats_suivi as $index => $etat): 
                            $isActive = ($index === $etat_val);
                            $classes = $isActive ? $etat['active_cls'] : $etat['inactive_cls'];
                        ?>
                            <div class="flex-1 flex flex-col items-center justify-center py-2 px-1 border rounded-xl transition-all duration-300 <?php echo $classes; ?>">
                                <i class="bi <?php echo $etat['icon']; ?> text-base md:text-lg mb-0.5 <?php echo $isActive ? '' : 'opacity-50'; ?>"></i> 
                                <span class="text-[8px] md:text-[9px] font-bold tracking-widest uppercase text-center leading-tight">
                                    <span class="md:hidden"><?php echo $etat['label_short']; ?></span>
                                    <span class="hidden md:inline"><?php echo $etat['label_long']; ?></span>
                                </span>
                            </div>
                            <?php if ($index < 2): ?>
                                <div class="flex items-center justify-center text-slate-600">
                                    <i class="bi bi-chevron-right text-sm"></i>
                                </div>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="flex-grow overflow-y-auto custom-scroll bg-transparent p-4 md:p-6 flex flex-col gap-4">
                    
                    <?php if ($etat_val == 2): ?>
                    <div class="flex-shrink-0 bg-gradient-to-r from-emerald-900/40 to-emerald-800/20 border border-emerald-700/50 rounded-xl p-3 flex items-start sm:items-center gap-3 shadow-sm shadow-emerald-900/50 relative overflow-hidden">
                        <div class="absolute -right-4 -top-4 text-emerald-500 opacity-20">
                            <i class="bi bi-check-circle-fill" style="font-size: 5rem;"></i>
                        </div>
                        <div class="w-8 h-8 rounded-full bg-gradient-to-br from-emerald-800 to-emerald-900 text-emerald-400 flex items-center justify-center shrink-0 z-10 border border-emerald-600 shadow-inner">
                            <i class="bi bi-bag-check-fill text-lg"></i>
                        </div>
                        <div class="z-10">
                            <h3 class="text-sm font-black text-emerald-400 tracking-tight">Matériel prêt !</h3>
                            <p class="text-emerald-300/90 text-xs mt-0.5 font-medium leading-tight">
                                <?php if ($fin_timestamp > 0): ?>
                                    Réparation finalisée le <strong><?php echo date('d/m/Y', $fin_timestamp); ?></strong>.<br>
                                <?php endif; ?>
                                À récupérer dans votre boutique de <strong class="uppercase text-emerald-200 bg-emerald-900/80 px-1 rounded"><?php echo $agence; ?></strong>.
                            </p>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="grid grid-cols-1 md:grid-cols-12 gap-3 flex-shrink-0">
                        
                        <div class="md:col-span-6 flex items-center gap-3 p-3 rounded-xl bg-slate-800 border border-slate-700 shadow-sm transition-shadow">
                            <div class="w-10 h-10 rounded-lg bg-gradient-to-br from-blue-900/50 to-blue-800/30 text-blue-400 flex items-center justify-center shrink-0 border border-blue-700/50 shadow-inner">
                                <i class="bi bi-person-fill text-lg"></i>
                            </div>
                            <div class="overflow-hidden">
                                <span class="text-[9px] font-bold text-slate-500 uppercase tracking-widest block mb-0.5">Client</span>
                                <p class="text-sm font-black text-slate-200 truncate" title="<?php echo htmlspecialchars($data['client']); ?>"><?php echo htmlspecialchars($data['client']); ?></p>
                            </div>
                        </div>
                        
                        <div class="md:col-span-6 flex items-center gap-3 p-3 rounded-xl bg-slate-800 border border-slate-700 shadow-sm transition-shadow">
                            <div class="w-10 h-10 rounded-lg bg-gradient-to-br from-indigo-900/50 to-indigo-800/30 text-indigo-400 flex items-center justify-center shrink-0 border border-indigo-700/50 shadow-inner">
                                <i class="bi bi-laptop text-lg"></i>
                            </div>
                            <div class="overflow-hidden">
                                <span class="text-[9px] font-bold text-slate-500 uppercase tracking-widest block mb-0.5">Matériel</span>
                                <p class="text-sm font-black text-slate-200 truncate" title="<?php echo htmlspecialchars($data['materiel'] ?: 'Non spécifié'); ?>"><?php echo htmlspecialchars($data['materiel'] ?: 'Non spécifié'); ?></p>
                            </div>
                        </div>

                        <div class="md:col-span-8 flex items-center gap-3 p-3 rounded-xl bg-slate-800 border border-slate-700 shadow-sm transition-shadow">
                            <div class="w-10 h-10 rounded-lg bg-gradient-to-br from-emerald-900/50 to-emerald-800/30 text-emerald-400 flex items-center justify-center shrink-0 border border-emerald-700/50 shadow-inner">
                                <i class="bi bi-tools text-lg"></i>
                            </div>
                            <div class="overflow-hidden w-full">
                                <span class="text-[9px] font-bold text-slate-500 uppercase tracking-widest block mb-0.5">Interventions</span>
                                <p class="text-sm font-bold text-slate-300 leading-tight">
                                    <?php echo nl2br(htmlspecialchars($data['chantier'] ?: 'Standard')); ?>
                                </p>
                            </div>
                        </div>

                        <div class="md:col-span-4 flex items-center gap-3 p-3 rounded-xl bg-slate-800 border border-slate-700 shadow-sm transition-shadow">
                            <div class="w-10 h-10 rounded-lg bg-gradient-to-br from-amber-900/50 to-amber-800/30 text-amber-400 flex items-center justify-center shrink-0 border border-amber-700/50 shadow-inner">
                                <i class="bi bi-calendar-event text-lg"></i>
                            </div>
                            <div class="overflow-hidden">
                                <span class="text-[9px] font-bold text-slate-500 uppercase tracking-widest block mb-0.5">Délai estimé</span>
                                <p class="text-sm font-black text-slate-200 truncate">
                                    <?php echo !empty($data['delai']) ? htmlspecialchars($data['delai']) . " jours" : "-"; ?>
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="flex-grow flex flex-col min-h-[180px]">
                        <div class="flex items-center gap-2 mb-2 flex-shrink-0">
                            <div class="w-6 h-6 rounded bg-gradient-to-br from-blue-600 to-indigo-700 text-white flex items-center justify-center shadow-md shadow-blue-900/50">
                                <i class="bi bi-activity text-xs"></i>
                            </div>
                            <h2 class="text-[10px] font-black text-white uppercase tracking-widest">Journal de suivi</h2>
                            <div class="h-px bg-slate-700 flex-grow ml-2"></div>
                        </div>
                        
                        <div class="bg-slate-800/80 rounded-xl border border-slate-700/80 p-4 shadow-sm flex-grow overflow-hidden flex flex-col">
                            <div class="relative border-l-2 border-slate-700 ml-2 pb-1 overflow-y-auto custom-scroll flex-grow pr-2">
                                <?php
                                $avance_raw = $data['avance'] ?? '';
                                $avance_raw = trim($avance_raw, '|');
                                $entries = array_filter(explode('|', $avance_raw), function($val) { return trim($val) !== ''; });
                                
                                if (empty($entries)): 
                                    $empty_msg = "Dossier créé. En attente de prise en charge...";
                                    if ($etat_val == 1) $empty_msg = "Intervention en cours...";
                                    elseif ($etat_val == 2) $empty_msg = ($fin_timestamp > 0) ? "Intervention terminée le " . date('d/m/Y', $fin_timestamp) . "." : "L'intervention est terminée.";
                                ?>
                                    <div class="pl-4 relative">
                                        <div class="absolute -left-[9px] top-0.5 w-3.5 h-3.5 rounded-full bg-slate-700 border-[3px] border-slate-600"></div>
                                        <p class="text-[11px] text-slate-400 font-medium italic"><?php echo $empty_msg; ?></p>
                                    </div>
                                <?php else:
                                    $total_entries = count($entries);
                                    $current_idx = 0;
                                    
                                    foreach ($entries as $entry):
                                        $current_idx++;
                                        $is_last = ($current_idx === $total_entries);
                                        
                                        $l_parts = explode('->', $entry);
                                        $date_log = isset($l_parts[0]) ? trim(ltrim($l_parts[0], '|')) : '-';
                                        $comment_log = isset($l_parts[1]) ? trim($l_parts[1]) : 'Mise à jour en cours';
                                ?>
                                    <div class="pl-5 pb-4 relative group last:pb-1 pt-0.5">
                                        <?php if ($is_last): ?>
                                            <div class="absolute -left-[9px] top-0.5 w-3.5 h-3.5">
                                                <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-500 opacity-75"></span>
                                                <span class="relative inline-flex rounded-full h-3.5 w-3.5 bg-blue-500 border-[2px] border-blue-200 shadow-[0_0_10px_rgba(59,130,246,0.8)]"></span>
                                            </div>
                                        <?php else: ?>
                                            <div class="absolute -left-[9px] top-0.5 w-3.5 h-3.5 rounded-full bg-slate-800 border-[3px] border-slate-600 group-hover:border-slate-500 transition-colors"></div>
                                        <?php endif; ?>
                                        
                                        <div class="mb-1">
                                            <span class="inline-block px-2 py-0.5 <?php echo $is_last ? 'bg-blue-600 border border-blue-400 shadow-[0_0_10px_rgba(59,130,246,0.4)] text-white' : 'bg-slate-700 border border-slate-600 text-slate-400'; ?> rounded text-[9px] font-bold tracking-wide">
                                                <?php echo htmlspecialchars($date_log); ?>
                                            </span>
                                        </div>
                                        <p class="text-[11px] <?php echo $is_last ? 'text-slate-200 font-bold' : 'text-slate-400 font-medium'; ?> leading-relaxed mt-1">
                                            <?php echo nl2br(htmlspecialchars($comment_log)); ?>
                                        </p>
                                    </div>
                                <?php endforeach; endif; ?>
                            </div>
                        </div>
                    </div>

                    <?php if ($devis || $total_ttc_calcule > 0 || $facture_finale > 0): ?>
                    <div class="flex-shrink-0 flex flex-col sm:flex-row justify-between items-center p-3.5 bg-gradient-to-r from-slate-800 to-slate-800/50 border border-slate-700 rounded-xl shadow-sm hover:shadow transition-shadow">
                        <div class="flex items-center gap-3 mb-2 sm:mb-0">
                            <div class="w-8 h-8 rounded-full <?php echo ($facture_finale > 0) ? 'bg-emerald-900/50 text-emerald-400 border-emerald-700/50' : 'bg-slate-700 text-slate-300 border-slate-600'; ?> flex items-center justify-center shrink-0 border shadow-sm">
                                <i class="bi bi-receipt text-sm"></i>
                            </div>
                            <div>
                                <p class="text-[9px] font-bold <?php echo ($facture_finale > 0) ? 'text-emerald-500/80' : 'text-slate-500'; ?> uppercase tracking-widest mb-0.5">
                                    <?php echo ($facture_finale > 0) ? 'Dossier Facturé' : 'Devis / Facturation'; ?>
                                </p>
                                <?php if ($devis && $facture_finale == 0): ?>
                                    <p class="text-[10px] font-bold text-slate-300">
                                        Réf. #<?php echo htmlspecialchars($devis['id']); ?> 
                                        <?php 
                                            $date_devis = $devis['date'];
                                            if ($date_devis) echo "<span class='text-slate-600 font-normal mx-1'>|</span>" . (is_numeric($date_devis) ? date('d/m/Y', $date_devis) : htmlspecialchars($date_devis));
                                        ?>
                                    </p>
                                <?php elseif ($facture_finale > 0): ?>
                                    <p class="text-[10px] font-bold text-emerald-400/80">
                                        Montant validé et enregistré
                                    </p>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="text-right">
                            <?php if ($facture_finale > 0): ?>
                                <span class="text-[9px] font-bold text-emerald-500 uppercase tracking-widest block mb-0.5 flex items-center justify-end gap-1">
                                    <i class="bi bi-check2-all"></i> Montant Final Facturé
                                </span>
                                <div class="text-xl font-black text-emerald-400 tracking-tight drop-shadow-[0_0_8px_rgba(52,211,153,0.3)]">
                                    <?php echo number_format($facture_finale, 2, ',', ' '); ?> <span class="text-sm text-emerald-500/70 font-bold">€</span>
                                </div>
                            <?php else: ?>
                                <span class="text-[9px] font-bold text-slate-500 uppercase tracking-widest block mb-0.5">Montant TTC estimé</span>
                                <div class="text-xl font-black text-slate-200 tracking-tight">
                                    <?php echo number_format($total_ttc_calcule, 2, ',', ' '); ?> <span class="text-sm text-slate-400 font-bold">€</span>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                </div>

                <div class="bg-slate-900/90 px-5 py-3 border-t border-slate-800 flex justify-between items-center print-hide flex-shrink-0 z-10">
                    <div class="flex items-center gap-2 text-slate-500">
                        <i class="bi bi-shield-check text-sm"></i>
                        <span class="text-[9px] font-bold uppercase tracking-widest">Plateforme sécurisée</span>
                    </div>
                    <button onclick="window.print()" class="px-4 py-1.5 bg-slate-800 border border-slate-700 text-slate-300 rounded-md text-[10px] font-bold hover:bg-slate-700 hover:text-blue-400 hover:border-slate-600 transition-all shadow-sm flex items-center gap-1.5">
                        <i class="bi bi-printer"></i> Imprimer
                    </button>
                </div>
            </div>
            
            <div class="mt-3 text-slate-600 text-[9px] font-bold uppercase tracking-[0.2em] text-center print-hide relative z-10 pb-2">
                Microtiq - Solutions Informatiques
            </div>

        <?php endif; ?>
    </main>

    <footer class="bg-[#0a0f1c] py-12 border-t border-white/5 print-hide">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center md:text-left">
            <div class="flex flex-col md:flex-row justify-between items-center gap-8">
                <div>
                    <span class="text-xl font-black text-white uppercase">MICRO<span class="text-blue-500">TIQ</span></span>
                    <p class="mt-2 text-slate-500 text-sm">Votre partenaire informatique de confiance.</p>
                </div>
                <div class="flex gap-6 text-xs font-bold uppercase tracking-widest text-slate-400">
                    <a href="/particulier/index.html" class="hover:text-white transition-colors">Accueil</a>
                    <a href="/particulier/services.html" class="hover:text-white transition-colors">Expertises</a>
                    <a href="/particulier/mentions.html" class="hover:text-white transition-colors">Mentions légales</a>
                </div>
            </div>
            <p class="mt-12 text-[10px] text-slate-600 font-bold uppercase tracking-[0.2em] text-center md:text-left">
                © <span id="current-year"></span> MICROTIQ.COM - TOUS DROITS RÉSERVÉS.
            </p>
        </div>
    </footer>

    <script>
        // Initialisation des icônes Lucide
        lucide.createIcons();
        document.getElementById('current-year').textContent = new Date().getFullYear();

        // Gestion du menu mobile
        const menuBtn = document.getElementById('mobile-menu-btn');
        const mobileMenu = document.getElementById('mobile-menu');
        const menuIcon = document.getElementById('menu-icon');
        const closeIcon = document.getElementById('close-icon');

        function toggleMenu() {
            const isClosed = mobileMenu.classList.contains('opacity-0');
            if (isClosed) {
                mobileMenu.classList.remove('opacity-0', 'invisible', 'h-0');
                mobileMenu.classList.add('opacity-100', 'visible', 'h-auto');
                menuIcon.classList.add('hidden');
                closeIcon.classList.remove('hidden');
            } else {
                mobileMenu.classList.add('opacity-0', 'invisible', 'h-0');
                mobileMenu.classList.remove('opacity-100', 'visible', 'h-auto');
                menuIcon.classList.remove('hidden');
                closeIcon.classList.add('hidden');
            }
        }

        if(menuBtn) {
            menuBtn.addEventListener('click', toggleMenu);
        }

        // Fermer le menu mobile quand on clique sur un lien
        document.querySelectorAll('.mobile-link').forEach(link => {
            link.addEventListener('click', () => {
                if (!mobileMenu.classList.contains('opacity-0')) {
                    toggleMenu();
                }
            });
        });
    </script>
</body>
</html>