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

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

// Delete payment
if ($action === 'delete' && $id) {
    $paiement = $db->prepare("SELECT * FROM paiements WHERE id=?");
    $paiement->execute([$id]);
    $paiement = $paiement->fetch();
    if (!$paiement) { flash('error', 'Paiement introuvable.'); redirect('/paiements.php'); }
    
    $inscriptionId = $paiement['inscription_id'];
    
    // Delete payment
    $db->prepare("DELETE FROM paiements WHERE id=?")->execute([$id]);
    
    // Recalculate inscription payment status
    $ins = $db->prepare("SELECT * FROM inscriptions WHERE id=?");
    $ins->execute([$inscriptionId]);
    $ins = $ins->fetch();
    
    if ($ins) {
        $totalPaye = $db->prepare("SELECT COALESCE(SUM(montant),0) FROM paiements WHERE inscription_id=?");
        $totalPaye->execute([$inscriptionId]);
        $tp = $totalPaye->fetchColumn();
        $statutPaiement = $tp >= $ins['prix_total'] ? 'paye' : ($tp > 0 ? 'partiel' : 'impaye');
        $db->prepare("UPDATE inscriptions SET montant_paye=?, statut_paiement=? WHERE id=?")->execute([$tp, $statutPaiement, $inscriptionId]);
    }
    
    logAction($_SESSION['user_id'], 'paiement_delete', "Suppression paiement #{$id}");
    flash('success', 'Paiement supprimé.');
    redirect('/paiements.php');
}

// Save payment
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $editId = intval($_POST['id'] ?? 0);
    $inscriptionId = intval($_POST['inscription_id'] ?? 0);
    $montant = floatval($_POST['montant'] ?? 0);
    $mode = $_POST['mode_paiement'] ?? 'especes';
    $reference = sanitize($_POST['reference_paiement'] ?? '');
    $date = $_POST['date_paiement'] ?? date('Y-m-d');
    $notes = sanitize($_POST['notes'] ?? '');

    if ($montant <= 0) {
        flash('error', 'Le montant doit être supérieur à 0.');
        redirect('/paiements.php');
    }

    // Get voyageur from inscription
    $ins = $db->prepare("SELECT * FROM inscriptions WHERE id=?");
    $ins->execute([$inscriptionId]);
    $ins = $ins->fetch();
    if (!$ins) { flash('error', 'Inscription introuvable.'); redirect('/paiements.php'); }

    if ($editId) {
        // Update existing payment
        $db->prepare("UPDATE paiements SET inscription_id=?, voyageur_id=?, montant=?, mode_paiement=?, reference_paiement=?, date_paiement=?, notes=? WHERE id=?")
            ->execute([$inscriptionId, $ins['voyageur_id'], $montant, $mode, $reference, $date, $notes, $editId]);
        logAction($_SESSION['user_id'], 'paiement_update', "Modification paiement #{$editId}");
        flash('success', 'Paiement modifié avec succès.');
    } else {
        // Create new payment
        $db->prepare("INSERT INTO paiements (inscription_id, voyageur_id, montant, mode_paiement, reference_paiement, date_paiement, notes, created_by) VALUES (?,?,?,?,?,?,?,?)")
            ->execute([$inscriptionId, $ins['voyageur_id'], $montant, $mode, $reference, $date, $notes, $_SESSION['user_id']]);
        logAction($_SESSION['user_id'], 'paiement_create', "Paiement de $montant MAD pour inscription #$inscriptionId");
        flash('success', 'Paiement enregistré avec succès.');
    }

    // Update inscription payment status
    $totalPaye = $db->prepare("SELECT COALESCE(SUM(montant),0) FROM paiements WHERE inscription_id=?");
    $totalPaye->execute([$inscriptionId]);
    $tp = $totalPaye->fetchColumn();
    $statutPaiement = $tp >= $ins['prix_total'] ? 'paye' : ($tp > 0 ? 'partiel' : 'impaye');
    $db->prepare("UPDATE inscriptions SET montant_paye=?, statut_paiement=? WHERE id=?")->execute([$tp, $statutPaiement, $inscriptionId]);

    redirect('/paiements.php');
}

// Receipt
if ($action === 'recu' && $id) {
    $p = $db->prepare("SELECT pa.*, v.nom, v.prenom, v.cin, v.telephone, v.adresse, v.ville, pr.nom as programme_nom, pr.type as programme_type, i.num_dossier, i.formule, i.prix_total, i.montant_paye FROM paiements pa JOIN voyageurs v ON pa.voyageur_id=v.id JOIN inscriptions i ON pa.inscription_id=i.id JOIN programmes pr ON i.programme_id=pr.id WHERE pa.id=?");
    $p->execute([$id]);
    $p = $p->fetch();
    if (!$p) { flash('error', 'Paiement introuvable.'); redirect('/paiements.php'); }
    $ag = getAgencyInfo();
?>
<!DOCTYPE html>
<html lang="fr"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reçu de paiement - <?= sanitize($ag['agence_nom'] ?? APP_NAME) ?></title>
<link href="<?= APP_URL ?>/assets/css/bootstrap.min.css" rel="stylesheet">
<link href="<?= APP_URL ?>/assets/css/bootstrap-icons.min.css" rel="stylesheet">
<style>
    body { background: #f8f9fa; }
    .receipt { max-width: 800px; margin: 20px auto; background: white; padding: 40px; border: 2px solid #dee2e6; }
    .receipt-header { border-bottom: 3px solid #065f46; padding-bottom: 20px; margin-bottom: 20px; }
    @media print { body { background: white; } .receipt { border: none; margin: 0; } .no-print { display: none; } }
</style>
</head><body>
<div class="no-print text-center py-3">
    <button onclick="window.print()" class="btn btn-primary"><i class="bi bi-printer me-2"></i>Imprimer</button>
    <a href="<?= APP_URL ?>/paiements.php" class="btn btn-outline-secondary ms-2">Retour</a>
</div>
<div class="receipt">
    <div class="receipt-header">
        <div class="row align-items-center">
            <div class="col-8">
                <?php if (!empty($ag['agence_logo'])): ?>
                    <img src="<?= APP_URL ?>/uploads/<?= sanitize($ag['agence_logo']) ?>" alt="Logo" style="max-height:60px;" class="mb-1">
                <?php endif; ?>
                <h3 class="text-success mb-1"><?= sanitize($ag['agence_nom'] ?? 'UpTours') ?></h3>
                <p class="text-muted mb-0"><?= sanitize($ag['agence_slogan'] ?? '') ?></p>
                <p class="small text-muted mb-0"><?= sanitize($ag['agence_adresse'] ?? '') ?> – <?= sanitize($ag['agence_ville'] ?? '') ?></p>
                <p class="small text-muted mb-0">Tél: <?= sanitize($ag['agence_telephone'] ?? '') ?> <?= !empty($ag['agence_fax']) ? '| Fax: '.sanitize($ag['agence_fax']) : '' ?></p>
                <p class="small text-muted mb-0"><?= !empty($ag['agence_email']) ? sanitize($ag['agence_email']) : '' ?> <?= !empty($ag['agence_site_web']) ? '| '.sanitize($ag['agence_site_web']) : '' ?></p>
                <?php if (!empty($ag['agence_ice'])): ?><p class="small text-muted mb-0">ICE: <?= sanitize($ag['agence_ice']) ?> | IF: <?= sanitize($ag['agence_if'] ?? '') ?> | RC: <?= sanitize($ag['agence_rc'] ?? '') ?></p><?php endif; ?>
            </div>
            <div class="col-4 text-end">
                <h5 class="mb-1">REÇU DE PAIEMENT</h5>
                <p class="text-muted mb-0">N° <?= str_pad($p['id'], 6, '0', STR_PAD_LEFT) ?></p>
            </div>
        </div>
    </div>
    <div class="row mb-4">
        <div class="col-6">
            <strong>Client:</strong><br>
            <?= sanitize($p['prenom'].' '.$p['nom']) ?><br>
            CIN: <?= sanitize($p['cin'] ?: '-') ?><br>
            Tél: <?= sanitize($p['telephone'] ?: '-') ?><br>
            <?= sanitize($p['ville'] ?: '') ?>
        </div>
        <div class="col-6 text-end">
            <strong>Date:</strong> <?= formatDate($p['date_paiement']) ?><br>
            <strong>Dossier:</strong> <?= sanitize($p['num_dossier']) ?><br>
            <strong>Programme:</strong> <?= sanitize($p['programme_nom']) ?><br>
            <strong>Chambre:</strong> <?= ucfirst($p['formule']) ?>
        </div>
    </div>
    <table class="table table-bordered">
        <thead class="table-light"><tr><th>Description</th><th class="text-end">Montant</th></tr></thead>
        <tbody>
            <tr><td>Paiement - <?= ucfirst($p['mode_paiement']) ?> <?= $p['reference_paiement'] ? '(Réf: '.$p['reference_paiement'].')' : '' ?></td><td class="text-end fw-bold"><?= formatMoney($p['montant']) ?></td></tr>
        </tbody>
        <tfoot>
            <tr><td class="text-end">Prix total du programme:</td><td class="text-end"><?= formatMoney($p['prix_total']) ?></td></tr>
            <tr><td class="text-end">Total payé à ce jour:</td><td class="text-end text-success fw-bold"><?= formatMoney($p['montant_paye']) ?></td></tr>
            <tr><td class="text-end">Reste à payer:</td><td class="text-end text-danger fw-bold"><?= formatMoney($p['prix_total'] - $p['montant_paye']) ?></td></tr>
        </tfoot>
    </table>
    <?php if ($p['notes']): ?><p><strong>Notes:</strong> <?= sanitize($p['notes']) ?></p><?php endif; ?>
    <?php if (!empty($ag['agence_banque_nom'])): ?>
    <div class="border rounded p-2 mb-3 small">
        <strong>Coordonnées bancaires:</strong> <?= sanitize($ag['agence_banque_nom']) ?> – <?= sanitize($ag['agence_banque_agence'] ?? '') ?><br>
        RIB: <span class="font-monospace"><?= sanitize($ag['agence_banque_rib'] ?? '') ?></span>
        <?php if (!empty($ag['agence_banque_iban'])): ?> | IBAN: <span class="font-monospace"><?= sanitize($ag['agence_banque_iban']) ?></span><?php endif; ?>
    </div>
    <?php endif; ?>
    <div class="row mt-5">
        <div class="col-6"><p class="border-top pt-2">Signature du client</p></div>
        <div class="col-6 text-end"><p class="border-top pt-2">Cachet et signature de l'agence</p></div>
    </div>
    <p class="text-center text-muted small mt-4"><?= sanitize($ag['agence_nom'] ?? APP_NAME) ?> | <?= sanitize($ag['agence_telephone'] ?? '') ?> | <?= sanitize($ag['agence_email'] ?? '') ?> – Reçu généré le <?= date('d/m/Y H:i') ?></p>
</div>
</body></html>
<?php
    exit;
}

// Form
if ($action === 'add' || $action === 'edit') {
    $paiement = null;
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM paiements WHERE id=?");
        $stmt->execute([$id]);
        $paiement = $stmt->fetch();
        if (!$paiement) { flash('error', 'Paiement introuvable.'); redirect('/paiements.php'); }
    }
    
    $preselectedInscription = $paiement ? $paiement['inscription_id'] : intval($_GET['inscription_id'] ?? 0);
    $inscriptions = $db->query("SELECT i.*, v.nom, v.prenom, p.nom as programme_nom FROM inscriptions i JOIN voyageurs v ON i.voyageur_id=v.id JOIN programmes p ON i.programme_id=p.id WHERE i.status != 'annule' ORDER BY i.created_at DESC")->fetchAll();
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/paiements.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-cash-coin me-2"></i><?= $paiement ? 'Modifier le paiement' : 'Nouveau paiement' ?></div>
        <div class="card-body p-4">
            <form method="POST">
                <input type="hidden" name="id" value="<?= $paiement['id'] ?? '' ?>">
                <div class="row g-3">
                    <div class="col-md-12">
                        <label class="form-label">Inscription *</label>
                        <select name="inscription_id" class="form-select select2" required>
                            <option value="">-- Sélectionner --</option>
                            <?php foreach ($inscriptions as $ins): ?>
                                <option value="<?= $ins['id'] ?>" <?= $preselectedInscription==$ins['id']?'selected':'' ?>>
                                    <?= sanitize($ins['num_dossier'].' - '.$ins['prenom'].' '.$ins['nom'].' | '.$ins['programme_nom'].' | Reste: '.formatMoney($ins['prix_total']-$ins['montant_paye'])) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Montant (MAD) *</label>
                        <input type="number" step="0.01" name="montant" class="form-control" value="<?= $paiement['montant'] ?? '' ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Mode de paiement</label>
                        <select name="mode_paiement" class="form-select">
                            <option value="especes" <?= ($paiement['mode_paiement']??'')=='especes'?'selected':'' ?>>Espèces</option>
                            <option value="virement" <?= ($paiement['mode_paiement']??'')=='virement'?'selected':'' ?>>Virement bancaire</option>
                            <option value="cheque" <?= ($paiement['mode_paiement']??'')=='cheque'?'selected':'' ?>>Chèque</option>
                            <option value="carte" <?= ($paiement['mode_paiement']??'')=='carte'?'selected':'' ?>>Carte bancaire</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Date</label>
                        <input type="date" name="date_paiement" class="form-control" value="<?= $paiement['date_paiement'] ?? date('Y-m-d') ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Référence</label>
                        <input type="text" name="reference_paiement" class="form-control" placeholder="N° chèque, virement, etc." value="<?= sanitize($paiement['reference_paiement'] ?? '') ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Notes</label>
                        <input type="text" name="notes" class="form-control" value="<?= sanitize($paiement['notes'] ?? '') ?>">
                    </div>
                </div>
                <div class="d-flex gap-2 mt-4">
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Enregistrer</button>
                    <a href="<?= APP_URL ?>/paiements.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>
<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// List
$search = $_GET['search'] ?? '';
$modeFilter = $_GET['mode'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));

$where = "WHERE 1=1";
$params = [];
if ($search) { $where .= " AND (v.nom LIKE ? OR v.prenom LIKE ? OR pa.reference_paiement LIKE ? OR i.num_dossier LIKE ?)"; $s="%$search%"; $params=[$s,$s,$s,$s]; }
if ($modeFilter) { $where .= " AND pa.mode_paiement=?"; $params[] = $modeFilter; }

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

$stmt = $db->prepare("SELECT pa.*, v.nom, v.prenom, i.num_dossier, p.nom as programme_nom, p.type as programme_type FROM paiements pa JOIN voyageurs v ON pa.voyageur_id=v.id JOIN inscriptions i ON pa.inscription_id=i.id JOIN programmes p ON i.programme_id=p.id $where ORDER BY pa.created_at DESC LIMIT {$pagination['per_page']} OFFSET {$pagination['offset']}");
$stmt->execute($params);
$paiements = $stmt->fetchAll();

$totalMontant = $db->prepare("SELECT COALESCE(SUM(pa.montant),0) FROM paiements pa JOIN voyageurs v ON pa.voyageur_id=v.id JOIN inscriptions i ON pa.inscription_id=i.id $where");
$totalMontant->execute($params);
$totalMontant = $totalMontant->fetchColumn();
?>

<div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
    <form class="d-flex gap-2 flex-wrap" method="GET">
        <div class="input-group" style="width:250px;">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" name="search" class="form-control" placeholder="Rechercher..." value="<?= sanitize($search) ?>">
        </div>
        <select name="mode" class="form-select" style="width:160px;">
            <option value="">Tous modes</option>
            <option value="especes" <?= $modeFilter=='especes'?'selected':'' ?>>Espèces</option>
            <option value="virement" <?= $modeFilter=='virement'?'selected':'' ?>>Virement</option>
            <option value="cheque" <?= $modeFilter=='cheque'?'selected':'' ?>>Chèque</option>
            <option value="carte" <?= $modeFilter=='carte'?'selected':'' ?>>Carte</option>
        </select>
        <button class="btn btn-outline-primary">Filtrer</button>
    </form>
    <div class="d-flex gap-2 align-items-center">
        <span class="badge bg-success fs-6 py-2 px-3">Total: <?= formatMoney($totalMontant) ?></span>
        <a href="<?= APP_URL ?>/paiements.php?action=add" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Nouveau paiement</a>
    </div>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover">
            <thead><tr>
                <th>Date</th><th>Dossier</th><th>Voyageur</th><th>Programme</th><th>Montant</th><th>Mode</th><th>Référence</th><th>Actions</th>
            </tr></thead>
            <tbody>
            <?php foreach ($paiements as $p): ?>
                <tr>
                    <td><?= formatDate($p['date_paiement']) ?></td>
                    <td><strong><?= sanitize($p['num_dossier'] ?: '-') ?></strong></td>
                    <td><a href="<?= APP_URL ?>/voyageurs.php?action=view&id=<?= $p['voyageur_id'] ?>"><?= sanitize($p['prenom'].' '.$p['nom']) ?></a></td>
                    <td><small><?= sanitize($p['programme_nom']) ?></small></td>
                    <td class="fw-bold text-success"><?= formatMoney($p['montant']) ?></td>
                    <td><span class="badge bg-light text-dark"><?= ucfirst($p['mode_paiement']) ?></span></td>
                    <td><small><?= sanitize($p['reference_paiement'] ?: '-') ?></small></td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="<?= APP_URL ?>/paiements.php?action=recu&id=<?= $p['id'] ?>" class="btn btn-outline-primary" title="Reçu" target="_blank"><i class="bi bi-printer"></i></a>
                            <a href="<?= APP_URL ?>/paiements.php?action=edit&id=<?= $p['id'] ?>" class="btn btn-outline-warning" title="Modifier"><i class="bi bi-pencil"></i></a>
                            <a href="<?= APP_URL ?>/paiements.php?action=delete&id=<?= $p['id'] ?>" class="btn btn-outline-danger" title="Supprimer" onclick="return confirmDelete('Supprimer ce paiement ?')"><i class="bi bi-trash"></i></a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($paiements)): ?><tr><td colspan="8" class="text-center text-muted py-4">Aucun paiement</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card-footer">
        <?= renderPagination($pagination, APP_URL.'/paiements.php?search='.urlencode($search).'&mode='.urlencode($modeFilter)) ?>
    </div>
</div>

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