<?php
$pageTitle = 'Factures';
require_once __DIR__ . '/includes/header.php';
$db = getDB();

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

// Generate new Facture Number
function generateFactureNumber($db) {
    $prefix = 'FAC-' . date('Ym') . '-';
    $stmt = $db->query("SELECT numero FROM factures 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) {
    $fact = $db->prepare("SELECT * FROM factures WHERE id=?");
    $fact->execute([$id]);
    $facture = $fact->fetch();
    if (!$facture) { flash('error', 'Facture introuvable.'); redirect('/factures.php'); }
    
    // Check if payments are linked
    $hasPaiements = $db->prepare("SELECT COUNT(*) FROM paiements WHERE facture_id=?");
    $hasPaiements->execute([$id]);
    if ($hasPaiements->fetchColumn() > 0) {
        flash('error', 'Impossible de supprimer cette facture car elle contient des paiements. Supprimez d\'abord les paiements.');
        redirect('/factures.php');
    }
    
    $db->prepare("DELETE FROM factures WHERE id=?")->execute([$id]);
    logAction($_SESSION['user_id'], 'facture_delete', "Facture supprimée: {$facture['numero']} (ID: $id)");
    flash('success', 'Facture supprimée avec succès.');
    redirect('/factures.php');
}

// --- Sauvegarde (Ajout/Modification) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($action === 'add' || $action === 'edit')) {
    $editId = intval($_POST['id'] ?? 0);
    $voyageurId = intval($_POST['voyageur_id'] ?? 0);
    $dateFacture = $_POST['date_facture'] ?? date('Y-m-d');
    $dateEcheance = $_POST['date_echeance'] ?? date('Y-m-d', strtotime('+15 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 de la facture
    $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 ? "/factures.php?action=edit&id=$editId" : '/factures.php?action=add');
    }

    $montantHT = 0;
    
    $db->beginTransaction();
    try {
        if ($editId) {
            // Update
            $db->prepare("UPDATE factures SET voyageur_id=?, date_facture=?, date_echeance=?, statut=?, notes=?, conditions=?, updated_at=datetime('now') WHERE id=?")
               ->execute([$voyageurId, $dateFacture, $dateEcheance, $statut, $notes, $conditions, $editId]);
            $factureId = $editId;
            // Clear old lines
            $db->prepare("DELETE FROM facture_lignes WHERE facture_id=?")->execute([$factureId]);
            logAction($_SESSION['user_id'], 'facture_update', "Facture modifiée: ID $factureId");
        } else {
            // Insert
            $numero = generateFactureNumber($db);
            $db->prepare("INSERT INTO factures (numero, voyageur_id, date_facture, date_echeance, statut, notes, conditions, created_by) VALUES (?,?,?,?,?,?,?,?)")
               ->execute([$numero, $voyageurId, $dateFacture, $dateEcheance, $statut, $notes, $conditions, $_SESSION['user_id']]);
            $factureId = $db->lastInsertId();
            logAction($_SESSION['user_id'], 'facture_create', "Nouvelle facture créée: $numero");
        }
        
        // Insert lines
        $stmtLigne = $db->prepare("INSERT INTO facture_lignes (facture_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([$factureId, 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 factures SET montant_ht=?, montant_remise=?, taux_tva=?, montant_tva=?, montant_ttc=? WHERE id=?")
           ->execute([$montantHT, $montantRemise, $tauxTva, $montantTVA, $montantTTC, $factureId]);
           
        $db->commit();
        flash('success', 'Facture enregistrée avec succès.');
        redirect('/factures.php?action=view&id='.$factureId);
    } catch (Exception $e) {
        $db->rollBack();
        flash('error', 'Erreur lors de la sauvegarde: ' . $e->getMessage());
        redirect($editId ? "/factures.php?action=edit&id=$editId" : '/factures.php?action=add');
    }
}

// --- Encaisser un paiement depuis la facture ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'add_payment' && $id) {
    $montant = floatval($_POST['montant'] ?? 0);
    $mode = $_POST['mode_paiement'] ?? 'especes';
    $reference = sanitize($_POST['reference_paiement'] ?? '');
    $date = $_POST['date_paiement'] ?? date('Y-m-d');
    
    $fact = $db->prepare("SELECT * FROM factures WHERE id=?");
    $fact->execute([$id]);
    $facture = $fact->fetch();
    if (!$facture) { flash('error', 'Facture introuvable.'); redirect('/factures.php'); }
    
    if ($montant <= 0) { flash('error', 'Montant invalide.'); redirect("/factures.php?action=view&id=$id"); }
    
    $db->prepare("INSERT INTO paiements (facture_id, voyageur_id, montant, mode_paiement, reference_paiement, date_paiement, created_by) VALUES (?,?,?,?,?,?,?)")
       ->execute([$id, $facture['voyageur_id'], $montant, $mode, $reference, $date, $_SESSION['user_id']]);
       
    // Re-calculer statut facture
    $totalPaye = $db->prepare("SELECT COALESCE(SUM(montant),0) FROM paiements WHERE facture_id=?")->execute([$id])->fetchColumn();
    $statut = $totalPaye >= $facture['montant_ttc'] ? 'payee' : 'partielle';
    $db->prepare("UPDATE factures SET statut=? WHERE id=?")->execute([$statut, $id]);
    
    flash('success', 'Paiement enregistré pour la facture.');
    redirect("/factures.php?action=view&id=$id");
}

// --- Formulaire ---
if ($action === 'add' || $action === 'edit') {
    $facture = null;
    $lignes = [];
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM factures WHERE id=?");
        $stmt->execute([$id]);
        $facture = $stmt->fetch();
        if (!$facture) { flash('error', 'Introuvable.'); redirect('/factures.php'); }
        
        $stmtL = $db->prepare("SELECT * FROM facture_lignes WHERE facture_id=?");
        $stmtL->execute([$id]);
        $lignes = $stmtL->fetchAll();
    } else {
        $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'] ?? ($facture['voyageur_id'] ?? 0));
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/factures.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-ruled me-2"></i><?= $facture ? 'Modifier la Facture' : 'Nouvelle Facture' ?></div>
        <div class="card-body p-4">
            <form method="POST" id="form-facture">
                <input type="hidden" name="id" value="<?= $facture['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 facturation *</label>
                        <input type="date" name="date_facture" class="form-control" value="<?= $facture['date_facture'] ?? date('Y-m-d') ?>" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Date d'échéance *</label>
                        <input type="date" name="date_echeance" class="form-control" value="<?= $facture['date_echeance'] ?? date('Y-m-d', strtotime('+15 days')) ?>" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Statut *</label>
                        <select name="statut" class="form-select" required>
                            <option value="brouillon" <?= ($facture['statut']??'')=='brouillon'?'selected':'' ?>>Brouillon</option>
                            <option value="envoye" <?= ($facture['statut']??'')=='envoye'?'selected':'' ?>>Envoyée</option>
                            <option value="partielle" <?= ($facture['statut']??'')=='partielle'?'selected':'' ?>>Paiement Partiel</option>
                            <option value="payee" <?= ($facture['statut']??'')=='payee'?'selected':'' ?>>Payée</option>
                            <option value="annulee" <?= ($facture['statut']??'')=='annulee'?'selected':'' ?>>Annulée</option>
                        </select>
                    </div>
                </div>

                <h5 class="mb-3 border-bottom pb-2">Lignes de la facture</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="Prestation, voyage, billet...">
                        </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 la facture)</label>
                                <textarea name="notes" class="form-control" rows="2"><?= sanitize($facture['notes'] ?? '') ?></textarea>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Conditions de paiement</label>
                                <textarea name="conditions" class="form-control" rows="2"><?= sanitize($facture['conditions'] ?? 'Paiement à réception de la facture. Aucun escompte pour paiement anticipé.') ?></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="<?= $facture['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" <?= ($facture['taux_tva']??0)==0?'selected':'' ?>>0 %</option>
                                    <option value="10" <?= ($facture['taux_tva']??0)==10?'selected':'' ?>>10 %</option>
                                    <option value="14" <?= ($facture['taux_tva']??0)==14?'selected':'' ?>>14 %</option>
                                    <option value="20" <?= ($facture['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 ?>/factures.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 la facture ---
if ($action === 'print' && $id) {
    $fact = $db->prepare("SELECT f.*, v.nom, v.prenom, v.adresse, v.ville, v.telephone, v.cin FROM factures f JOIN voyageurs v ON f.voyageur_id=v.id WHERE f.id=?");
    $fact->execute([$id]);
    $facture = $fact->fetch();
    if (!$facture) { flash('error', 'Facture introuvable.'); redirect('/factures.php'); }
    
    $lignes = $db->prepare("SELECT * FROM facture_lignes WHERE facture_id=?");
    $lignes->execute([$id]);
    $lignes = $lignes->fetchAll();
    
    // Get payments for this invoice
    $stmtPaiements = $db->prepare("SELECT * FROM paiements WHERE facture_id=?");
    $stmtPaiements->execute([$id]);
    $paiements = $stmtPaiements->fetchAll();
    
    $totalPaye = array_sum(array_column($paiements, 'montant'));
    $reste = $facture['montant_ttc'] - $totalPaye;
    
    $ag = getAgencyInfo();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Facture <?= sanitize($facture['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 ?>/factures.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">FACTURE</h1>
                <h4 class="text-muted mb-3">N° <?= sanitize($facture['numero']) ?></h4>
                <div><strong>Date :</strong> <?= date('d/m/Y', strtotime($facture['date_facture'])) ?></div>
                <div><strong>Échéance :</strong> <?= date('d/m/Y', strtotime($facture['date_echeance'])) ?></div>
            </div>
        </div>

        <div class="row mb-5">
            <div class="col-6">
                <?php if ($facture['statut'] == 'payee'): ?>
                <div class="text-success border border-success p-2 d-inline-block rounded fw-bold mt-2 text-uppercase" style="border-width: 3px !important; transform: rotate(-5deg);">
                    PAYÉE
                </div>
                <?php endif; ?>
            </div>
            <div class="col-6">
                <div class="border p-3 rounded bg-light">
                    <h6 class="text-muted mb-2 border-bottom pb-1">Facturé à :</h6>
                    <strong><?= sanitize($facture['prenom'].' '.$facture['nom']) ?></strong><br>
                    CIN : <?= sanitize($facture['cin'] ?: '-') ?><br>
                    Tél : <?= sanitize($facture['telephone'] ?: '-') ?><br>
                    <?= sanitize($facture['adresse'] ?: '') ?> <?= sanitize($facture['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-6">
                <?php if ($facture['notes']): ?>
                    <p class="mb-2 text-muted small"><strong>Notes :</strong><br><?= nl2br(sanitize($facture['notes'])) ?></p>
                <?php endif; ?>
                <?php if ($facture['conditions']): ?>
                    <p class="mb-0 text-muted small"><strong>Conditions :</strong><br><?= nl2br(sanitize($facture['conditions'])) ?></p>
                <?php endif; ?>
                
                <?php if (!empty($paiements)): ?>
                <div class="mt-4 border p-2 rounded bg-light">
                    <h6 class="small fw-bold mb-2">Historique des paiements :</h6>
                    <table class="table table-sm table-borderless small mb-0">
                        <?php foreach($paiements as $p): ?>
                        <tr>
                            <td><?= date('d/m/Y', strtotime($p['date_paiement'])) ?></td>
                            <td><?= ucfirst($p['mode_paiement']) ?> <?= $p['reference_paiement'] ? '('.sanitize($p['reference_paiement']).')' : '' ?></td>
                            <td class="text-end"><?= number_format($p['montant'], 2, ',', ' ') ?> MAD</td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                </div>
                <?php endif; ?>
            </div>
            <div class="col-6">
                <table class="table table-sm table-borderless">
                    <tr>
                        <td><strong>Total HT :</strong></td>
                        <td class="text-end"><?= number_format($facture['montant_ht'], 2, ',', ' ') ?> MAD</td>
                    </tr>
                    <?php if ($facture['montant_remise'] > 0): ?>
                    <tr class="text-danger">
                        <td>Remise :</td>
                        <td class="text-end">- <?= number_format($facture['montant_remise'], 2, ',', ' ') ?> MAD</td>
                    </tr>
                    <?php endif; ?>
                    <tr class="border-bottom">
                        <td>TVA (<?= $facture['taux_tva'] ?>%) :</td>
                        <td class="text-end"><?= number_format($facture['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($facture['montant_ttc'], 2, ',', ' ') ?> MAD</strong></td>
                    </tr>
                    <?php if ($totalPaye > 0): ?>
                    <tr class="text-success">
                        <td>Total Payé :</td>
                        <td class="text-end">- <?= number_format($totalPaye, 2, ',', ' ') ?> MAD</td>
                    </tr>
                    <tr class="fs-6 fw-bold <?= $reste > 0 ? 'text-danger' : 'text-success' ?> border-top">
                        <td class="pt-2">Reste à payer :</td>
                        <td class="text-end pt-2"><?= number_format(max(0, $reste), 2, ',', ' ') ?> MAD</td>
                    </tr>
                    <?php endif; ?>
                </table>
            </div>
        </div>

        <div class="row mb-2">
            <div class="col-12">
                <p>Arrêtée la présente facture à la somme de : <strong><?= ucfirst(numberToWords(floor($facture['montant_ttc']))) ?> Dirhams<?php 
                    $centimes = round(($facture['montant_ttc'] - floor($facture['montant_ttc'])) * 100);
                    if ($centimes > 0) {
                        echo " et " . numberToWords($centimes) . " Centimes";
                    }
                ?>.</strong></p>
            </div>
        </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) {
    $fact = $db->prepare("SELECT f.*, v.nom, v.prenom, v.cin, v.telephone, v.email, u.full_name as createur FROM factures f JOIN voyageurs v ON f.voyageur_id=v.id LEFT JOIN users u ON f.created_by=u.id WHERE f.id=?");
    $fact->execute([$id]);
    $facture = $fact->fetch();
    if (!$facture) { flash('error', 'Introuvable.'); redirect('/factures.php'); }
    
    $lignes = $db->prepare("SELECT * FROM facture_lignes WHERE facture_id=?");
    $lignes->execute([$id]);
    $lignes = $lignes->fetchAll();
    
    $stmtPaiements = $db->prepare("SELECT * FROM paiements WHERE facture_id=? ORDER BY date_paiement DESC");
    $stmtPaiements->execute([$id]);
    $paiements = $stmtPaiements->fetchAll();
    
    $totalPaye = array_sum(array_column($paiements, 'montant'));
    $reste = $facture['montant_ttc'] - $totalPaye;
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/factures.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 ?>/factures.php?action=print&id=<?= $id ?>" class="btn btn-secondary" target="_blank"><i class="bi bi-printer me-1"></i>Imprimer</a>
            <?php if ($facture['statut'] !== 'payee' && $facture['statut'] !== 'annulee'): ?>
                <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#paymentModal"><i class="bi bi-cash me-1"></i>Encaisser</button>
                <a href="<?= APP_URL ?>/factures.php?action=edit&id=<?= $id ?>" class="btn btn-warning"><i class="bi bi-pencil me-1"></i>Modifier</a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Modal Paiement -->
    <div class="modal fade" id="paymentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" action="<?= APP_URL ?>/factures.php?action=add_payment&id=<?= $id ?>">
                    <div class="modal-header">
                        <h5 class="modal-title">Enregistrer un paiement</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-info">Reste à payer : <strong><?= formatMoney($reste) ?></strong></div>
                        <div class="mb-3">
                            <label class="form-label">Montant (MAD)</label>
                            <input type="number" step="0.01" name="montant" class="form-control" value="<?= $reste ?>" max="<?= $reste ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Mode de paiement</label>
                            <select name="mode_paiement" class="form-select">
                                <option value="especes">Espèces</option>
                                <option value="virement">Virement bancaire</option>
                                <option value="cheque">Chèque</option>
                                <option value="carte">Carte bancaire</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Date</label>
                            <input type="date" name="date_paiement" class="form-control" value="<?= date('Y-m-d') ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Référence (optionnel)</label>
                            <input type="text" name="reference_paiement" class="form-control" placeholder="N° chèque, etc.">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                        <button type="submit" class="btn btn-success">Enregistrer</button>
                    </div>
                </form>
            </div>
        </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 de la Facture</span>
                    <?php 
                        $badges = ['brouillon'=>'secondary', 'envoye'=>'primary', 'partielle'=>'warning', 'payee'=>'success', 'annulee'=>'danger'];
                        $bColor = $badges[$facture['statut']] ?? 'secondary';
                    ?>
                    <span class="badge bg-<?= $bColor ?>"><?= ucfirst($facture['statut']) ?></span>
                </div>
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-sm-6">
                            <h4 class="mb-0 text-success"><?= sanitize($facture['numero']) ?></h4>
                            <small class="text-muted">Créée par <?= sanitize($facture['createur']) ?> le <?= formatDateTime($facture['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($facture['date_facture'])) ?></div>
                            <div><strong>Échéance :</strong> <span class="<?= strtotime($facture['date_echeance']) < time() && $facture['statut']!='payee' ? 'text-danger fw-bold' : '' ?>"><?= date('d/m/Y', strtotime($facture['date_echeance'])) ?></span></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=<?= $facture['voyageur_id'] ?>" class="text-decoration-none"><?= sanitize($facture['prenom'].' '.$facture['nom']) ?></a></strong><br>
                        CIN: <?= sanitize($facture['cin']?:'-') ?> | Tél: <?= sanitize($facture['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>
            
            <?php if (!empty($paiements)): ?>
            <div class="card table-card">
                <div class="card-header"><i class="bi bi-cash-stack me-2"></i>Paiements reçus</div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead><tr><th>Date</th><th>Mode</th><th>Référence</th><th>Montant</th></tr></thead>
                        <tbody>
                            <?php foreach($paiements as $p): ?>
                            <tr>
                                <td><?= date('d/m/Y', strtotime($p['date_paiement'])) ?></td>
                                <td><span class="badge bg-light text-dark"><?= ucfirst($p['mode_paiement']) ?></span></td>
                                <td><?= sanitize($p['reference_paiement'] ?: '-') ?></td>
                                <td class="text-end text-success fw-bold"><?= formatMoney($p['montant']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>
        </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($facture['montant_ht']) ?></span></div>
                    <?php if ($facture['montant_remise'] > 0): ?>
                    <div class="d-flex justify-content-between mb-2 text-danger"><span class="text-muted">Remise</span><span>- <?= formatMoney($facture['montant_remise']) ?></span></div>
                    <?php endif; ?>
                    <div class="d-flex justify-content-between mb-3 border-bottom pb-3"><span class="text-muted">TVA (<?= $facture['taux_tva'] ?>%)</span><span><?= formatMoney($facture['montant_tva']) ?></span></div>
                    <div class="d-flex justify-content-between fs-4 fw-bold text-primary mb-3"><span>TTC</span><span><?= formatMoney($facture['montant_ttc']) ?></span></div>
                    
                    <div class="d-flex justify-content-between mb-2 text-success"><span>Payé</span><span>- <?= formatMoney($totalPaye) ?></span></div>
                    <div class="d-flex justify-content-between fs-5 fw-bold <?= $reste > 0 ? 'text-danger' : 'text-success' ?> border-top pt-2">
                        <span>Reste</span><span><?= formatMoney(max(0, $reste)) ?></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 (f.numero LIKE ? OR v.nom LIKE ? OR v.prenom LIKE ?)"; $s="%$search%"; $params=[$s,$s,$s]; }
if ($statutFilter) { $where .= " AND f.statut=?"; $params[] = $statutFilter; }

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

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

// Get total remaining across all invoices
$totalReste = $db->query("SELECT COALESCE(SUM(montant_ttc),0) FROM factures WHERE statut != 'annulee'")->fetchColumn();
$totalPayeQuery = $db->query("SELECT COALESCE(SUM(montant),0) FROM paiements WHERE facture_id IS NOT NULL")->fetchColumn();
$globalReste = $totalReste - $totalPayeQuery;
?>

<div class="row g-3 mb-4">
    <div class="col-md-4">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="stat-icon bg-primary bg-opacity-10 text-primary"><i class="bi bi-file-earmark-ruled"></i></div>
                <div><small class="text-muted d-block">Factures</small><h4 class="mb-0 fw-bold"><?= $pagination['total'] ?></h4></div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="stat-icon bg-danger bg-opacity-10 text-danger"><i class="bi bi-exclamation-triangle"></i></div>
                <div><small class="text-muted d-block">Créances clients (Reste à payer)</small><h5 class="mb-0 fw-bold text-danger"><?= formatMoney(max(0, $globalReste)) ?></h5></div>
            </div>
        </div>
    </div>
    <div class="col-md-4 d-flex align-items-center">
        <a href="<?= APP_URL ?>/factures.php?action=add" class="btn btn-primary btn-lg w-100 h-100 d-flex align-items-center justify-content-center gap-2" style="border-radius:16px;">
            <i class="bi bi-plus-lg"></i> Nouvelle Facture
        </a>
    </div>
</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ée</option>
                    <option value="partielle" <?= $statutFilter=='partielle'?'selected':'' ?>>Paiement Partiel</option>
                    <option value="payee" <?= $statutFilter=='payee'?'selected':'' ?>>Payée</option>
                    <option value="annulee" <?= $statutFilter=='annulee'?'selected':'' ?>>Annulée</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 ?>/factures.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>Échéance</th>
                    <th>Client</th>
                    <th>Montant TTC</th>
                    <th>Statut</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($facturesList as $f): ?>
                <tr>
                    <td><strong><a href="<?= APP_URL ?>/factures.php?action=view&id=<?= $f['id'] ?>" class="text-decoration-none"><?= sanitize($f['numero']) ?></a></strong></td>
                    <td><?= date('d/m/Y', strtotime($f['date_facture'])) ?></td>
                    <td>
                        <span class="<?= strtotime($f['date_echeance']) < time() && $f['statut']!='payee' && $f['statut']!='annulee' ? 'text-danger fw-bold' : '' ?>">
                            <?= date('d/m/Y', strtotime($f['date_echeance'])) ?>
                        </span>
                    </td>
                    <td><?= sanitize($f['prenom'].' '.$f['nom']) ?></td>
                    <td class="fw-bold"><?= formatMoney($f['montant_ttc']) ?></td>
                    <td>
                        <?php 
                            $badges = ['brouillon'=>'secondary', 'envoye'=>'primary', 'partielle'=>'warning', 'payee'=>'success', 'annulee'=>'danger'];
                            $bColor = $badges[$f['statut']] ?? 'secondary';
                        ?>
                        <span class="badge bg-<?= $bColor ?>"><?= ucfirst($f['statut']) ?></span>
                    </td>
                    <td class="text-end">
                        <div class="btn-group btn-group-sm">
                            <a href="<?= APP_URL ?>/factures.php?action=print&id=<?= $f['id'] ?>" class="btn btn-outline-secondary" target="_blank" title="Imprimer"><i class="bi bi-printer"></i></a>
                            <a href="<?= APP_URL ?>/factures.php?action=view&id=<?= $f['id'] ?>" class="btn btn-outline-primary" title="Détails"><i class="bi bi-eye"></i></a>
                            <?php if ($f['statut'] !== 'payee' && $f['statut'] !== 'annulee'): ?>
                            <a href="<?= APP_URL ?>/factures.php?action=edit&id=<?= $f['id'] ?>" class="btn btn-outline-warning" title="Modifier"><i class="bi bi-pencil"></i></a>
                            <a href="<?= APP_URL ?>/factures.php?action=delete&id=<?= $f['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($facturesList)): ?>
                <tr><td colspan="7" class="text-center py-5 text-muted"><i class="bi bi-inbox fs-1 d-block mb-2"></i>Aucune facture trouvée</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.'/factures.php?search='.urlencode($search).'&statut='.urlencode($statutFilter)) ?>
    </div>
    <?php endif; ?>
</div>

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