<?php
$pageTitle = 'Devis / Pro-forma';
require_once __DIR__ . '/includes/header.php';
$db = getDB();

$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

// Generate new Devis Number
function generateDevisNumber($db) {
    $prefix = 'DEV-' . date('Ym') . '-';
    $stmt = $db->query("SELECT numero FROM devis WHERE numero LIKE '$prefix%' ORDER BY numero DESC LIMIT 1");
    $last = $stmt->fetchColumn();
    if ($last) {
        $num = intval(substr($last, -4)) + 1;
    } else {
        $num = 1;
    }
    return $prefix . str_pad($num, 4, '0', STR_PAD_LEFT);
}

// --- Suppression ---
if ($action === 'delete' && $id) {
    $dev = $db->prepare("SELECT * FROM devis WHERE id=?");
    $dev->execute([$id]);
    $devis = $dev->fetch();
    if (!$devis) { flash('error', 'Devis introuvable.'); redirect('/devis.php'); }
    
    if ($devis['statut'] === 'facture') {
        flash('error', 'Impossible de supprimer un devis qui a déjà été facturé.');
        redirect('/devis.php');
    }
    
    // Begin transaction for safe deletion
    $db->beginTransaction();
    try {
        $db->prepare("DELETE FROM devis_lignes WHERE devis_id=?")->execute([$id]);
        $db->prepare("DELETE FROM devis WHERE id=?")->execute([$id]);
        $db->commit();
        
        logAction($_SESSION['user_id'], 'devis_delete', "Devis supprimé: {$devis['numero']} (ID: $id)");
        flash('success', 'Devis supprimé avec succès.');
    } catch (Exception $e) {
        $db->rollBack();
        flash('error', 'Erreur lors de la suppression: ' . $e->getMessage());
    }
    
    redirect('/devis.php');
}

// --- Sauvegarde (Ajout/Modification) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($action === 'add' || $action === 'edit')) {
    $editId = intval($_POST['id'] ?? 0);
    $voyageurId = intval($_POST['voyageur_id'] ?? 0);
    $dateDevis = $_POST['date_devis'] ?? date('Y-m-d');
    $dateValidite = $_POST['date_validite'] ?? date('Y-m-d', strtotime('+30 days'));
    $statut = $_POST['statut'] ?? 'brouillon';
    $notes = sanitize($_POST['notes'] ?? '');
    $conditions = sanitize($_POST['conditions'] ?? '');
    $tauxTva = floatval($_POST['taux_tva'] ?? 0);
    $montantRemise = floatval($_POST['montant_remise'] ?? 0);
    
    // Lignes du devis
    $descriptions = $_POST['l_desc'] ?? [];
    $quantites = $_POST['l_qty'] ?? [];
    $prixUnitaies = $_POST['l_prix'] ?? [];
    
    if (!$voyageurId || empty($descriptions)) {
        flash('error', 'Veuillez sélectionner un client et ajouter au moins une ligne.');
        redirect($editId ? "/devis.php?action=edit&id=$editId" : '/devis.php?action=add');
    }

    $montantHT = 0;
    
    $db->beginTransaction();
    try {
        if ($editId) {
            // Update
            $db->prepare("UPDATE devis SET voyageur_id=?, date_devis=?, date_validite=?, statut=?, notes=?, conditions=?, updated_at=datetime('now') WHERE id=?")
               ->execute([$voyageurId, $dateDevis, $dateValidite, $statut, $notes, $conditions, $editId]);
            $devisId = $editId;
            // Clear old lines
            $db->prepare("DELETE FROM devis_lignes WHERE devis_id=?")->execute([$devisId]);
            logAction($_SESSION['user_id'], 'devis_update', "Devis modifié: ID $devisId");
        } else {
            // Insert
            $numero = generateDevisNumber($db);
            $db->prepare("INSERT INTO devis (numero, voyageur_id, date_devis, date_validite, statut, notes, conditions, created_by) VALUES (?,?,?,?,?,?,?,?)")
               ->execute([$numero, $voyageurId, $dateDevis, $dateValidite, $statut, $notes, $conditions, $_SESSION['user_id']]);
            $devisId = $db->lastInsertId();
            logAction($_SESSION['user_id'], 'devis_create', "Nouveau devis créé: $numero");
        }
        
        // Insert lines
        $stmtLigne = $db->prepare("INSERT INTO devis_lignes (devis_id, description, quantite, prix_unitaire, total_ligne) VALUES (?,?,?,?,?)");
        for ($i=0; $i < count($descriptions); $i++) {
            if (empty(trim($descriptions[$i]))) continue;
            $q = floatval($quantites[$i] ?? 1);
            $pu = floatval($prixUnitaies[$i] ?? 0);
            $totalLigne = $q * $pu;
            $montantHT += $totalLigne;
            $stmtLigne->execute([$devisId, trim($descriptions[$i]), $q, $pu, $totalLigne]);
        }
        
        // Calcul TVA et Remise
        $montantHTApresRemise = max(0, $montantHT - $montantRemise);
        $montantTVA = $montantHTApresRemise * ($tauxTva / 100);
        $montantTTC = $montantHTApresRemise + $montantTVA;
        
        $db->prepare("UPDATE devis SET montant_ht=?, montant_remise=?, taux_tva=?, montant_tva=?, montant_ttc=? WHERE id=?")
           ->execute([$montantHT, $montantRemise, $tauxTva, $montantTVA, $montantTTC, $devisId]);
           
        $db->commit();
        flash('success', 'Devis enregistré avec succès.');
        redirect('/devis.php?action=view&id='.$devisId);
    } catch (Exception $e) {
        $db->rollBack();
        flash('error', 'Erreur lors de la sauvegarde: ' . $e->getMessage());
        redirect($editId ? "/devis.php?action=edit&id=$editId" : '/devis.php?action=add');
    }
}

// --- Convertir en Facture ---
if ($action === 'convert_to_invoice' && $id) {
    $db->beginTransaction();
    try {
        $dev = $db->prepare("SELECT * FROM devis WHERE id=?");
        $dev->execute([$id]);
        $devis = $dev->fetch();
        if (!$devis) throw new Exception("Devis introuvable.");
        
        // Check if already invoiced
        $factCheck = $db->prepare("SELECT id FROM factures WHERE devis_id=?");
        $factCheck->execute([$id]);
        if ($factCheck->fetchColumn()) throw new Exception("Ce devis a déjà été facturé.");
        
        // Generate Invoice Number
        $prefix = 'FAC-' . date('Ym') . '-';
        $stmtNum = $db->query("SELECT numero FROM factures WHERE numero LIKE '$prefix%' ORDER BY numero DESC LIMIT 1");
        $lastF = $stmtNum->fetchColumn();
        $numF = $lastF ? intval(substr($lastF, -4)) + 1 : 1;
        $numeroFacture = $prefix . str_pad($numF, 4, '0', STR_PAD_LEFT);
        
        // Create Invoice
        $db->prepare("INSERT INTO factures (numero, devis_id, voyageur_id, date_facture, date_echeance, statut, montant_ht, montant_remise, montant_tva, taux_tva, montant_ttc, notes, conditions, created_by) 
                      VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
           ->execute([
               $numeroFacture, $id, $devis['voyageur_id'], date('Y-m-d'), $devis['date_validite'], 'brouillon',
               $devis['montant_ht'], $devis['montant_remise'], $devis['montant_tva'], $devis['taux_tva'], $devis['montant_ttc'],
               $devis['notes'], $devis['conditions'], $_SESSION['user_id']
           ]);
        $factureId = $db->lastInsertId();
        
        // Copy lines
        $db->prepare("INSERT INTO facture_lignes (facture_id, description, quantite, prix_unitaire, total_ligne) 
                      SELECT ?, description, quantite, prix_unitaire, total_ligne FROM devis_lignes WHERE devis_id=?")
           ->execute([$factureId, $id]);
           
        // Update devis status
        $db->prepare("UPDATE devis SET statut='facture' WHERE id=?")->execute([$id]);
        
        $db->commit();
        logAction($_SESSION['user_id'], 'devis_convert', "Devis $id converti en facture $factureId");
        flash('success', 'Devis converti en facture avec succès.');
        redirect('/factures.php?action=view&id='.$factureId);
        
    } catch (Exception $e) {
        $db->rollBack();
        flash('error', $e->getMessage());
        redirect('/devis.php?action=view&id='.$id);
    }
}

// --- Formulaire ---
if ($action === 'add' || $action === 'edit') {
    $devis = null;
    $lignes = [];
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM devis WHERE id=?");
        $stmt->execute([$id]);
        $devis = $stmt->fetch();
        if (!$devis) { flash('error', 'Introuvable.'); redirect('/devis.php'); }
        
        $stmtL = $db->prepare("SELECT * FROM devis_lignes WHERE devis_id=?");
        $stmtL->execute([$id]);
        $lignes = $stmtL->fetchAll();
    } else {
        // Ligne vide par défaut
        $lignes = [['description'=>'', 'quantite'=>1, 'prix_unitaire'=>'']];
    }
    
    $voyageurs = $db->query("SELECT id, nom, prenom, cin, telephone FROM voyageurs ORDER BY nom")->fetchAll();
    $preselectedVoyageur = intval($_GET['voyageur_id'] ?? ($devis['voyageur_id'] ?? 0));
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/devis.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Retour</a>
    </div>
    
    <div class="card table-card">
        <div class="card-header"><i class="bi bi-file-earmark-text me-2"></i><?= $devis ? 'Modifier le Devis / Pro-forma' : 'Nouveau Devis / Pro-forma' ?></div>
        <div class="card-body p-4">
            <form method="POST" id="form-devis">
                <input type="hidden" name="id" value="<?= $devis['id'] ?? '' ?>">
                
                <div class="row g-3 mb-4">
                    <div class="col-md-6">
                        <label class="form-label">Client / Voyageur *</label>
                        <select name="voyageur_id" class="form-select select2" required>
                            <option value="">-- Sélectionner un client --</option>
                            <?php foreach ($voyageurs as $v): ?>
                                <option value="<?= $v['id'] ?>" <?= $preselectedVoyageur==$v['id']?'selected':'' ?>>
                                    <?= sanitize($v['nom'].' '.$v['prenom'].' (CIN: '.($v['cin']?:'-').')') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Date du devis *</label>
                        <input type="date" name="date_devis" class="form-control" value="<?= $devis['date_devis'] ?? date('Y-m-d') ?>" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Validité (Date) *</label>
                        <input type="date" name="date_validite" class="form-control" value="<?= $devis['date_validite'] ?? date('Y-m-d', strtotime('+30 days')) ?>" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Statut *</label>
                        <select name="statut" class="form-select" required>
                            <option value="brouillon" <?= ($devis['statut']??'')=='brouillon'?'selected':'' ?>>Brouillon</option>
                            <option value="envoye" <?= ($devis['statut']??'')=='envoye'?'selected':'' ?>>Envoyé au client</option>
                            <option value="accepte" <?= ($devis['statut']??'')=='accepte'?'selected':'' ?>>Accepté</option>
                            <option value="refuse" <?= ($devis['statut']??'')=='refuse'?'selected':'' ?>>Refusé</option>
                            <?php if(($devis['statut']??'')=='facture'): ?><option value="facture" selected>Facturé</option><?php endif; ?>
                        </select>
                    </div>
                </div>

                <h5 class="mb-3 border-bottom pb-2">Lignes du devis</h5>
                <div id="lignes-container">
                    <?php foreach($lignes as $index => $l): ?>
                    <div class="row g-2 mb-2 ligne-item align-items-end">
                        <div class="col-md-6">
                            <label class="form-label small text-muted">Description *</label>
                            <input type="text" name="l_desc[]" class="form-control" value="<?= sanitize($l['description']) ?>" required placeholder="Ex: Billet d'avion RAM Casa-Paris">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label small text-muted">Quantité *</label>
                            <input type="number" step="0.01" name="l_qty[]" class="form-control input-qty" value="<?= $l['quantite'] ?>" required onchange="calcTotal()">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label small text-muted">Prix Unitaire (MAD) *</label>
                            <input type="number" step="0.01" name="l_prix[]" class="form-control input-prix" value="<?= $l['prix_unitaire'] ?>" required onchange="calcTotal()">
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-outline-danger w-100" onclick="removeLigne(this)"><i class="bi bi-trash"></i></button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="mb-4 mt-2">
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="addLigne()"><i class="bi bi-plus-lg me-1"></i>Ajouter une ligne</button>
                </div>

                <div class="row g-3 mb-4">
                    <div class="col-md-8">
                        <div class="row g-3">
                            <div class="col-12">
                                <label class="form-label">Notes (Visibles sur le devis)</label>
                                <textarea name="notes" class="form-control" rows="2"><?= sanitize($devis['notes'] ?? 'Le présent devis est valable pour une durée de 30 jours.') ?></textarea>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Conditions de paiement</label>
                                <textarea name="conditions" class="form-control" rows="2"><?= sanitize($devis['conditions'] ?? 'Paiement à la confirmation. Acompte de 50% exigé.') ?></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="bg-light p-3 rounded">
                            <div class="d-flex justify-content-between mb-2 align-items-center">
                                <strong>Total HT:</strong>
                                <span id="display-ht">0.00 MAD</span>
                            </div>
                            <div class="d-flex justify-content-between mb-2 align-items-center">
                                <small>Remise (MAD):</small>
                                <input type="number" step="0.01" name="montant_remise" id="input-remise" class="form-control form-control-sm w-50 text-end" value="<?= $devis['montant_remise'] ?? '0' ?>" onchange="calcTotal()">
                            </div>
                            <div class="d-flex justify-content-between mb-2 align-items-center text-muted">
                                <small>TVA (%):</small>
                                <select name="taux_tva" id="input-tva" class="form-select form-select-sm w-50 text-end" onchange="calcTotal()">
                                    <option value="0" <?= ($devis['taux_tva']??0)==0?'selected':'' ?>>0 %</option>
                                    <option value="10" <?= ($devis['taux_tva']??0)==10?'selected':'' ?>>10 %</option>
                                    <option value="14" <?= ($devis['taux_tva']??0)==14?'selected':'' ?>>14 %</option>
                                    <option value="20" <?= ($devis['taux_tva']??0)==20?'selected':'' ?>>20 %</option>
                                </select>
                            </div>
                            <div class="d-flex justify-content-between mb-2 text-muted">
                                <small>Montant TVA:</small>
                                <span id="display-tva">0.00 MAD</span>
                            </div>
                            <hr>
                            <div class="d-flex justify-content-between fs-5">
                                <strong>Total TTC:</strong>
                                <strong class="text-primary" id="display-ttc">0.00 MAD</strong>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-primary"><i class="bi bi-save me-1"></i>Enregistrer</button>
                    <a href="<?= APP_URL ?>/devis.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>

    <script>
        function addLigne() {
            const container = document.getElementById('lignes-container');
            const row = document.createElement('div');
            row.className = 'row g-2 mb-2 ligne-item align-items-end';
            row.innerHTML = `
                <div class="col-md-6"><input type="text" name="l_desc[]" class="form-control" required placeholder="Description"></div>
                <div class="col-md-2"><input type="number" step="0.01" name="l_qty[]" class="form-control input-qty" value="1" required onchange="calcTotal()"></div>
                <div class="col-md-3"><input type="number" step="0.01" name="l_prix[]" class="form-control input-prix" required onchange="calcTotal()"></div>
                <div class="col-md-1"><button type="button" class="btn btn-outline-danger w-100" onclick="removeLigne(this)"><i class="bi bi-trash"></i></button></div>
            `;
            container.appendChild(row);
        }
        function removeLigne(btn) {
            const items = document.querySelectorAll('.ligne-item');
            if (items.length > 1) {
                btn.closest('.ligne-item').remove();
                calcTotal();
            } else {
                alert("Il faut au moins une ligne.");
            }
        }
        function calcTotal() {
            let totalHT = 0;
            document.querySelectorAll('.ligne-item').forEach(row => {
                const q = parseFloat(row.querySelector('.input-qty').value) || 0;
                const p = parseFloat(row.querySelector('.input-prix').value) || 0;
                totalHT += (q * p);
            });
            
            const remise = parseFloat(document.getElementById('input-remise').value) || 0;
            const tvaTaux = parseFloat(document.getElementById('input-tva').value) || 0;
            
            let totalHTApresRemise = Math.max(0, totalHT - remise);
            let montantTVA = totalHTApresRemise * (tvaTaux / 100);
            let totalTTC = totalHTApresRemise + montantTVA;

            document.getElementById('display-ht').textContent = totalHT.toFixed(2) + ' MAD';
            document.getElementById('display-tva').textContent = montantTVA.toFixed(2) + ' MAD';
            document.getElementById('display-ttc').textContent = totalTTC.toFixed(2) + ' MAD';
        }
        document.addEventListener('DOMContentLoaded', calcTotal);
    </script>
<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// --- Imprimer le devis ---
if ($action === 'print' && $id) {
    $dev = $db->prepare("SELECT d.*, v.nom, v.prenom, v.adresse, v.ville, v.telephone, v.cin FROM devis d JOIN voyageurs v ON d.voyageur_id=v.id WHERE d.id=?");
    $dev->execute([$id]);
    $devis = $dev->fetch();
    if (!$devis) { flash('error', 'Devis introuvable.'); redirect('/devis.php'); }
    
    $lignes = $db->prepare("SELECT * FROM devis_lignes WHERE devis_id=?");
    $lignes->execute([$id]);
    $lignes = $lignes->fetchAll();
    
    $ag = getAgencyInfo();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Devis <?= sanitize($devis['numero']) ?></title>
    <link href="<?= APP_URL ?>/assets/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; font-size: 14px; }
        .document-container { max-width: 800px; margin: 20px auto; background: white; padding: 40px; border: 1px solid #ccc; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .header-doc { border-bottom: 2px solid #065f46; padding-bottom: 20px; margin-bottom: 30px; }
        .doc-title { color: #065f46; font-weight: bold; text-transform: uppercase; letter-spacing: 2px; }
        .table-doc th { background-color: #f1f5f9; color: #333; }
        .footer-legal { font-size: 10px; text-align: center; border-top: 1px solid #eee; padding-top: 15px; margin-top: 50px; color: #666; }
        @media print { 
            body { background: white; margin: 0; } 
            .document-container { border: none; box-shadow: none; padding: 0; margin: 0; max-width: 100%; } 
            .no-print { display: none !important; } 
        }
    </style>
</head>
<body>
    <div class="no-print text-center py-3 bg-light border-bottom mb-4">
        <button onclick="window.print()" class="btn btn-primary"><i class="bi bi-printer me-2"></i>Imprimer / Sauvegarder PDF</button>
        <a href="<?= APP_URL ?>/devis.php?action=view&id=<?= $id ?>" class="btn btn-outline-secondary ms-2">Retour</a>
    </div>

    <div class="document-container">
        <div class="header-doc row align-items-center">
            <div class="col-6">
                <?php if (!empty($ag['agence_logo'])): ?>
                    <img src="<?= APP_URL ?>/uploads/<?= sanitize($ag['agence_logo']) ?>" alt="Logo" style="max-height:80px; max-width:250px;">
                <?php else: ?>
                    <h2 class="text-success fw-bold m-0"><?= sanitize($ag['agence_nom'] ?? APP_NAME) ?></h2>
                <?php endif; ?>
                <div class="mt-2">
                    <?= nl2br(sanitize($ag['agence_adresse'] ?? '')) ?><br>
                    Tél: <?= sanitize($ag['agence_telephone'] ?? '') ?><br>
                    Email: <?= sanitize($ag['agence_email'] ?? '') ?>
                </div>
            </div>
            <div class="col-6 text-end">
                <h1 class="doc-title mb-1">DEVIS / PRO-FORMA</h1>
                <h4 class="text-muted mb-3">N° <?= sanitize($devis['numero']) ?></h4>
                <div><strong>Date :</strong> <?= date('d/m/Y', strtotime($devis['date_devis'])) ?></div>
                <div><strong>Valable jusqu'au :</strong> <?= date('d/m/Y', strtotime($devis['date_validite'])) ?></div>
            </div>
        </div>

        <div class="row mb-5">
            <div class="col-6">
            </div>
            <div class="col-6">
                <div class="border p-3 rounded bg-light">
                    <h6 class="text-muted mb-2 border-bottom pb-1">Adressé à :</h6>
                    <strong><?= sanitize($devis['prenom'].' '.$devis['nom']) ?></strong><br>
                    CIN : <?= sanitize($devis['cin'] ?: '-') ?><br>
                    Tél : <?= sanitize($devis['telephone'] ?: '-') ?><br>
                    <?= sanitize($devis['adresse'] ?: '') ?> <?= sanitize($devis['ville'] ?: '') ?>
                </div>
            </div>
        </div>

        <table class="table table-bordered table-doc mb-4">
            <thead>
                <tr>
                    <th width="50%">Description</th>
                    <th width="15%" class="text-center">Qté</th>
                    <th width="15%" class="text-end">Prix U. (MAD)</th>
                    <th width="20%" class="text-end">Total (MAD)</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($lignes as $l): ?>
                <tr>
                    <td><?= nl2br(sanitize($l['description'])) ?></td>
                    <td class="text-center"><?= $l['quantite'] ?></td>
                    <td class="text-end"><?= number_format($l['prix_unitaire'], 2, ',', ' ') ?></td>
                    <td class="text-end"><?= number_format($l['total_ligne'], 2, ',', ' ') ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="row mb-4">
            <div class="col-7">
                <?php if ($devis['notes']): ?>
                    <p class="mb-2"><strong>Notes :</strong><br><?= nl2br(sanitize($devis['notes'])) ?></p>
                <?php endif; ?>
                <?php if ($devis['conditions']): ?>
                    <p class="mb-0"><strong>Conditions :</strong><br><?= nl2br(sanitize($devis['conditions'])) ?></p>
                <?php endif; ?>
            </div>
            <div class="col-5">
                <table class="table table-sm table-borderless">
                    <tr>
                        <td><strong>Total HT :</strong></td>
                        <td class="text-end"><?= number_format($devis['montant_ht'], 2, ',', ' ') ?> MAD</td>
                    </tr>
                    <?php if ($devis['montant_remise'] > 0): ?>
                    <tr class="text-danger">
                        <td>Remise :</td>
                        <td class="text-end">- <?= number_format($devis['montant_remise'], 2, ',', ' ') ?> MAD</td>
                    </tr>
                    <?php endif; ?>
                    <tr class="border-bottom">
                        <td>TVA (<?= $devis['taux_tva'] ?>%) :</td>
                        <td class="text-end"><?= number_format($devis['montant_tva'], 2, ',', ' ') ?> MAD</td>
                    </tr>
                    <tr>
                        <td class="fs-5 pt-2"><strong>Total TTC :</strong></td>
                        <td class="text-end fs-5 pt-2"><strong><?= number_format($devis['montant_ttc'], 2, ',', ' ') ?> MAD</strong></td>
                    </tr>
                </table>
            </div>
        </div>
        
        <div class="row mb-2">
            <div class="col-12">
                <p>Arrêté le présent devis à la somme de : <strong><?= ucfirst(numberToWords(floor($devis['montant_ttc']))) ?> Dirhams<?php 
                    $centimes = round(($devis['montant_ttc'] - floor($devis['montant_ttc'])) * 100);
                    if ($centimes > 0) {
                        echo " et " . numberToWords($centimes) . " Centimes";
                    }
                ?>.</strong></p>
            </div>
        </div>
        
        <div class="mt-5 pt-4">
            <p>Bon pour accord le : ____/____/________</p>
            <p>Signature du client (Précédée de la mention "Lu et approuvé")</p>
        </div>

        <div class="footer-legal">
            <strong><?= sanitize($ag['agence_nom'] ?? APP_NAME) ?></strong>
            <?php 
                $legal = [];
                if (!empty($ag['agence_rc'])) $legal[] = "RC : " . sanitize($ag['agence_rc']);
                if (!empty($ag['agence_patente'])) $legal[] = "Patente : " . sanitize($ag['agence_patente']);
                if (!empty($ag['agence_if'])) $legal[] = "IF : " . sanitize($ag['agence_if']);
                if (!empty($ag['agence_ice'])) $legal[] = "ICE : " . sanitize($ag['agence_ice']);
                if (!empty($ag['agence_licence'])) $legal[] = "Agrément : " . sanitize($ag['agence_licence']);
                if (!empty($legal)) echo "<br>" . implode(' | ', $legal);
                
                if (!empty($ag['agence_banque_nom']) && !empty($ag['agence_banque_rib'])) {
                    echo "<br>Banque : " . sanitize($ag['agence_banque_nom']) . " | RIB : " . sanitize($ag['agence_banque_rib']);
                }
            ?>
        </div>
    </div>
</body>
</html>
<?php
    exit;
}

// --- Vue Détails ---
if ($action === 'view' && $id) {
    $dev = $db->prepare("SELECT d.*, v.nom, v.prenom, v.cin, v.telephone, v.email, u.full_name as createur FROM devis d JOIN voyageurs v ON d.voyageur_id=v.id LEFT JOIN users u ON d.created_by=u.id WHERE d.id=?");
    $dev->execute([$id]);
    $devis = $dev->fetch();
    if (!$devis) { flash('error', 'Introuvable.'); redirect('/devis.php'); }
    
    $lignes = $db->prepare("SELECT * FROM devis_lignes WHERE devis_id=?");
    $lignes->execute([$id]);
    $lignes = $lignes->fetchAll();
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/devis.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Retour à la liste</a>
        <div class="d-flex gap-2">
            <a href="<?= APP_URL ?>/devis.php?action=print&id=<?= $id ?>" class="btn btn-secondary" target="_blank"><i class="bi bi-printer me-1"></i>Imprimer</a>
            <?php if ($devis['statut'] !== 'facture'): ?>
                <a href="<?= APP_URL ?>/devis.php?action=edit&id=<?= $id ?>" class="btn btn-warning"><i class="bi bi-pencil me-1"></i>Modifier</a>
                <a href="<?= APP_URL ?>/devis.php?action=convert_to_invoice&id=<?= $id ?>" class="btn btn-success" onclick="return confirm('Convertir ce devis en facture définitive ?')"><i class="bi bi-file-earmark-check me-1"></i>Convertir en Facture</a>
                <a href="<?= APP_URL ?>/devis.php?action=delete&id=<?= $id ?>" class="btn btn-danger" onclick="return confirmDelete()"><i class="bi bi-trash me-1"></i>Supprimer</a>
            <?php else: ?>
                <button class="btn btn-success" disabled><i class="bi bi-check-circle me-1"></i>Déjà Facturé</button>
            <?php endif; ?>
        </div>
    </div>

    <div class="row g-4">
        <div class="col-md-8">
            <div class="card table-card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span><i class="bi bi-info-circle me-2"></i>Détails du Devis</span>
                    <?php 
                        $badges = ['brouillon'=>'secondary', 'envoye'=>'primary', 'accepte'=>'success', 'refuse'=>'danger', 'facture'=>'dark'];
                        $bColor = $badges[$devis['statut']] ?? 'secondary';
                    ?>
                    <span class="badge bg-<?= $bColor ?>"><?= ucfirst($devis['statut']) ?></span>
                </div>
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-sm-6">
                            <h4 class="mb-0 text-success"><?= sanitize($devis['numero']) ?></h4>
                            <small class="text-muted">Créé par <?= sanitize($devis['createur']) ?> le <?= formatDateTime($devis['created_at']) ?></small>
                        </div>
                        <div class="col-sm-6 text-sm-end mt-3 mt-sm-0">
                            <div><strong>Date :</strong> <?= date('d/m/Y', strtotime($devis['date_devis'])) ?></div>
                            <div><strong>Valable jusqu'au :</strong> <?= date('d/m/Y', strtotime($devis['date_validite'])) ?></div>
                        </div>
                    </div>
                    
                    <div class="bg-light p-3 rounded mb-4">
                        <h6 class="text-muted mb-2">Client</h6>
                        <strong class="fs-5"><a href="<?= APP_URL ?>/voyageurs.php?action=view&id=<?= $devis['voyageur_id'] ?>" class="text-decoration-none"><?= sanitize($devis['prenom'].' '.$devis['nom']) ?></a></strong><br>
                        CIN: <?= sanitize($devis['cin']?:'-') ?> | Tél: <?= sanitize($devis['telephone']?:'-') ?>
                    </div>

                    <table class="table table-bordered mb-0">
                        <thead class="table-light">
                            <tr><th>Description</th><th class="text-center">Qté</th><th class="text-end">Prix U.</th><th class="text-end">Total</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach($lignes as $l): ?>
                            <tr>
                                <td><?= nl2br(sanitize($l['description'])) ?></td>
                                <td class="text-center"><?= $l['quantite'] ?></td>
                                <td class="text-end"><?= formatMoney($l['prix_unitaire']) ?></td>
                                <td class="text-end"><?= formatMoney($l['total_ligne']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card table-card sticky-top" style="top: 80px;">
                <div class="card-header bg-light"><i class="bi bi-calculator me-2"></i>Récapitulatif</div>
                <div class="card-body">
                    <div class="d-flex justify-content-between mb-2"><span class="text-muted">Total HT</span><span><?= formatMoney($devis['montant_ht']) ?></span></div>
                    <?php if ($devis['montant_remise'] > 0): ?>
                    <div class="d-flex justify-content-between mb-2 text-danger"><span class="text-muted">Remise</span><span>- <?= formatMoney($devis['montant_remise']) ?></span></div>
                    <?php endif; ?>
                    <div class="d-flex justify-content-between mb-3 border-bottom pb-3"><span class="text-muted">TVA (<?= $devis['taux_tva'] ?>%)</span><span><?= formatMoney($devis['montant_tva']) ?></span></div>
                    <div class="d-flex justify-content-between fs-4 fw-bold text-primary"><span>TTC</span><span><?= formatMoney($devis['montant_ttc']) ?></span></div>
                </div>
            </div>
        </div>
    </div>
<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// --- Liste ---
$search = $_GET['search'] ?? '';
$statutFilter = $_GET['statut'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));

$where = "WHERE 1=1";
$params = [];
if ($search) { $where .= " AND (d.numero LIKE ? OR v.nom LIKE ? OR v.prenom LIKE ?)"; $s="%$search%"; $params=[$s,$s,$s]; }
if ($statutFilter) { $where .= " AND d.statut=?"; $params[] = $statutFilter; }

$total = $db->prepare("SELECT COUNT(*) FROM devis d JOIN voyageurs v ON d.voyageur_id=v.id $where");
$total->execute($params);
$pagination = paginate($total->fetchColumn(), 15, $page);

$stmt = $db->prepare("SELECT d.*, v.nom, v.prenom FROM devis d JOIN voyageurs v ON d.voyageur_id=v.id $where ORDER BY d.created_at DESC LIMIT {$pagination['per_page']} OFFSET {$pagination['offset']}");
$stmt->execute($params);
$devisList = $stmt->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="mb-0">Devis & Pro-formas</h3>
    <a href="<?= APP_URL ?>/devis.php?action=add" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Nouveau Devis</a>
</div>

<div class="card table-card mb-4">
    <div class="card-body py-3">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-4">
                <div class="input-group">
                    <span class="input-group-text bg-light"><i class="bi bi-search"></i></span>
                    <input type="text" name="search" class="form-control" placeholder="Numéro, client..." value="<?= sanitize($search) ?>">
                </div>
            </div>
            <div class="col-md-3">
                <select name="statut" class="form-select" onchange="this.form.submit()">
                    <option value="">Tous les statuts</option>
                    <option value="brouillon" <?= $statutFilter=='brouillon'?'selected':'' ?>>Brouillon</option>
                    <option value="envoye" <?= $statutFilter=='envoye'?'selected':'' ?>>Envoyé</option>
                    <option value="accepte" <?= $statutFilter=='accepte'?'selected':'' ?>>Accepté</option>
                    <option value="refuse" <?= $statutFilter=='refuse'?'selected':'' ?>>Refusé</option>
                    <option value="facture" <?= $statutFilter=='facture'?'selected':'' ?>>Facturé</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100"><i class="bi bi-funnel"></i> Filtrer</button>
            </div>
            <?php if($search || $statutFilter): ?>
            <div class="col-md-1">
                <a href="<?= APP_URL ?>/devis.php" class="btn btn-outline-secondary w-100"><i class="bi bi-x"></i></a>
            </div>
            <?php endif; ?>
        </form>
    </div>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead>
                <tr>
                    <th>Numéro</th>
                    <th>Date</th>
                    <th>Client</th>
                    <th>Montant TTC</th>
                    <th>Statut</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($devisList as $d): ?>
                <tr>
                    <td><strong><a href="<?= APP_URL ?>/devis.php?action=view&id=<?= $d['id'] ?>" class="text-decoration-none"><?= sanitize($d['numero']) ?></a></strong></td>
                    <td><?= date('d/m/Y', strtotime($d['date_devis'])) ?></td>
                    <td><?= sanitize($d['prenom'].' '.$d['nom']) ?></td>
                    <td class="fw-bold"><?= formatMoney($d['montant_ttc']) ?></td>
                    <td>
                        <?php 
                            $badges = ['brouillon'=>'secondary', 'envoye'=>'primary', 'accepte'=>'success', 'refuse'=>'danger', 'facture'=>'dark'];
                            $bColor = $badges[$d['statut']] ?? 'secondary';
                        ?>
                        <span class="badge bg-<?= $bColor ?>"><?= ucfirst($d['statut']) ?></span>
                    </td>
                    <td class="text-end">
                        <div class="btn-group btn-group-sm">
                            <a href="<?= APP_URL ?>/devis.php?action=print&id=<?= $d['id'] ?>" class="btn btn-outline-secondary" target="_blank" title="Imprimer"><i class="bi bi-printer"></i></a>
                            <a href="<?= APP_URL ?>/devis.php?action=view&id=<?= $d['id'] ?>" class="btn btn-outline-primary" title="Détails"><i class="bi bi-eye"></i></a>
                            <?php if ($d['statut'] !== 'facture'): ?>
                            <a href="<?= APP_URL ?>/devis.php?action=edit&id=<?= $d['id'] ?>" class="btn btn-outline-warning" title="Modifier"><i class="bi bi-pencil"></i></a>
                            <a href="<?= APP_URL ?>/devis.php?action=delete&id=<?= $d['id'] ?>" class="btn btn-outline-danger" title="Supprimer" onclick="return confirmDelete()"><i class="bi bi-trash"></i></a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($devisList)): ?>
                <tr><td colspan="6" class="text-center py-5 text-muted"><i class="bi bi-inbox fs-1 d-block mb-2"></i>Aucun devis trouvé</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($pagination['total_pages'] > 1): ?>
    <div class="card-footer border-0 bg-white pt-3 pb-2">
        <?= renderPagination($pagination, APP_URL.'/devis.php?search='.urlencode($search).'&statut='.urlencode($statutFilter)) ?>
    </div>
    <?php endif; ?>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
