<?php 
session_start();
$userprofil = $_SESSION['user'];
if (!$userprofil) {
    header("Location: login.php");
    exit();
}
include('includes/header.php');
require_once "includes/dbconn.php";

// Totaux
$total_revenu = $total_depense = $solde_final = 0;
$operations = [];

// Filtres
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

// Traitement AJAX
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    switch($_POST['action']) {
        case 'ajouter_depense':
        case 'ajouter_revenu':
            $type = $_POST['action'] == 'ajouter_revenu' ? 'revenu' : 'depense';
            $stmt = $conn->prepare("INSERT INTO caisse (type, libelle, montant, date_operation) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssds", $type, $_POST['libelle'], $_POST['montant'], $_POST['date']);
            echo $stmt->execute() ? "success" : "error";
            break;
        case 'supprimer_operation':
            if ($_POST['source'] == 'mensualite') {
                $conn->query("DELETE FROM mensualites WHERE id = ".intval($_POST['id']));
            } else {
                $conn->query("DELETE FROM caisse WHERE id = ".intval($_POST['id']));
            }
            echo "supprimé";
            break;
        case 'modifier_operation':
            $stmt = $conn->prepare("UPDATE caisse SET libelle=?, montant=?, date_operation=? WHERE id=?");
            $stmt->bind_param("sdsi", $_POST['libelle'], $_POST['montant'], $_POST['date'], $_POST['id']);
            echo $stmt->execute() ? "modifié" : "erreur";
            break;
    }
    exit;
}

// Conditions SQL
$cond = "";
if ($start_date) $cond .= " AND date_operation >= '$start_date'";
if ($end_date)   $cond .= " AND date_operation <= '$end_date'";

// Caisse
$res = $conn->query("SELECT *, 'caisse' AS source FROM caisse WHERE 1=1 $cond ORDER BY date_operation DESC");
while ($row = $res->fetch_assoc()) {
    if ($row['type']=='revenu') $total_revenu += $row['montant'];
    else                         $total_depense += $row['montant'];
    $operations[] = $row;
}

// Mensualités
$cond2 = "";
if ($start_date) $cond2 .= " AND m.date_paiement >= '$start_date'";
if ($end_date)   $cond2 .= " AND m.date_paiement <= '$end_date'";
$sql = "
 SELECT m.id, CONCAT('Mensualité : ', e.noms, ' ', e.prenom, ' – ', m.mois) AS libelle, m.montant, m.date_paiement AS date_operation,
        'revenu' AS type, 'mensualite' AS source
 FROM mensualites m
 JOIN etudiants e ON m.etudiant_id = e.id
 WHERE 1=1 $cond2";
$res2 = $conn->query($sql);
while ($row = $res2->fetch_assoc()) {
    $total_revenu += $row['montant'];
    $operations[] = $row;
}

// Lettres de règlement
$cond3 = "";
if ($start_date) $cond3 .= " AND date_reglement >= '$start_date'";
if ($end_date)   $cond3 .= " AND date_reglement <= '$end_date'";
$res3 = $conn->query("
 SELECT id, CONCAT('Lettre – ', objet) AS libelle, montant, date_reglement AS date_operation,
        'depense' AS type, 'reglement' AS source
 FROM lettres_reglement WHERE 1=1 $cond3");
while ($row = $res3->fetch_assoc()) {
    $total_depense += $row['montant'];
    $operations[] = $row;
}

// Tri date descendante
usort($operations, fn($a,$b)=>strtotime($b['date_operation'])-strtotime($a['date_operation']));
$solde_final = $total_revenu - $total_depense;
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion de Caisse</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary: #2B7A78;       /* Dark teal */
            --primary-light: #3AAFA9;  /* Medium teal */
            --primary-lighter: #DEF2F1; /* Light teal */
            --secondary: #17252A;      /* Dark blue */
            --accent: #FEFFFF;         /* White */
            --success: #28a745;
            --danger: #dc3545;
            --warning: #fd7e14;
            --info: #17a2b8;
        }
        
        body {
            background-color: #f8fafc;
            font-family: 'Poppins', sans-serif;
        }
        
        .card {
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: none;
            margin-bottom: 1.5rem;
            overflow: hidden;
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            color: white;
            font-weight: 600;
            padding: 0.8rem 1.2rem;
            border-bottom: none;
        }
        
        .badge-revenu {
            background-color: var(--success);
            color: white;
        }
        
        .badge-depense {
            background-color: var(--danger);
            color: white;
        }
        
        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
        }
        
        .table {
            margin-bottom: 0;
            font-size: 0.9rem;
        }
        
        .table th {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            font-weight: 500;
            padding: 0.8rem;
        }
        
        .table td {
            vertical-align: middle;
            padding: 0.8rem;
            border-color: #f1f5f9;
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(58, 175, 169, 0.1);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            border: none;
            padding: 0.5rem 1rem;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, var(--primary-light), var(--primary));
            transform: translateY(-2px);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #28a745, #218838);
            border: none;
            padding: 0.5rem 1rem;
            transition: all 0.3s;
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
            border: none;
            padding: 0.5rem 1rem;
            transition: all 0.3s;
        }
        
        .btn-warning {
            background: linear-gradient(135deg, #fd7e14, #e36209);
            border: none;
            padding: 0.5rem 1rem;
            transition: all 0.3s;
        }
        
        .btn-info {
            background: linear-gradient(135deg, #17a2b8, #138496);
            border: none;
            padding: 0.5rem 1rem;
            transition: all 0.3s;
        }
        
        .stat-card {
            text-align: center;
            padding: 1.2rem;
            border-radius: 10px;
            color: white;
            margin-bottom: 1.5rem;
            min-height: 120px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            box-shadow: 0 4px 8px rgba(0,0,0,0.05);
            transition: all 0.3s;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 16px rgba(0,0,0,0.1);
        }
        
        .stat-card i {
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
        }
        
        .stat-card h5 {
            font-weight: 600;
            margin-bottom: 0.3rem;
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .stat-card p {
            font-size: 1.3rem;
            font-weight: 700;
            margin-bottom: 0;
        }
        
        .action-buttons .btn {
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
            padding: 0.5rem 1rem;
        }
        
        /* Couleurs spécifiques pour les cartes stats */
        .stat-revenu {
            background: linear-gradient(135deg, #28a745, #218838);
        }
        
        .stat-depense {
            background: linear-gradient(135deg, #dc3545, #c82333);
        }
        
        .stat-solde {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
        }
        
        .page-title {
            color: var(--secondary);
            font-weight: 600;
            margin-bottom: 1.5rem;
            position: relative;
            padding-bottom: 0.5rem;
        }
        
        .page-title:after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 50px;
            height: 3px;
            background: var(--primary-light);
        }
        
        .form-control, .form-select {
            border-radius: 6px;
            padding: 0.5rem 0.75rem;
            border: 1px solid #e2e8f0;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-light);
            box-shadow: 0 0 0 0.2rem rgba(58, 175, 169, 0.25);
        }
        
        @media (max-width: 768px) {
            .action-buttons .btn {
                width: 100%;
                margin-right: 0;
            }
            
            .stat-card {
                min-height: auto;
                padding: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <div class="row mb-4">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center">
                    <h4 class="page-title">
                        <i class="bi bi-cash-stack me-2"></i>Gestion de Caisse
                    </h4>
                    <?php if ($_SESSION['user']['role'] == 'admin'): ?>
                    <div class="action-buttons">
                        <button class="btn btn-success" onclick="ajouterRevenu()">
                            <i class="bi bi-plus-circle me-1"></i> Revenu
                        </button>
                        <button class="btn btn-danger" onclick="ajouterDepense()">
                            <i class="bi bi-dash-circle me-1"></i> Dépense
                        </button>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Filtres -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-funnel me-2"></i> Filtres
            </div>
            <div class="card-body">
                <form method="get" class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">Date de début</label>
                        <input type="date" id="start_date" name="start_date" class="form-control" value="<?= $start_date ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Date de fin</label>
                        <input type="date" id="end_date" name="end_date" class="form-control" value="<?= $end_date ?>">
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button class="btn btn-primary w-100">
                            <i class="bi bi-funnel-fill me-1"></i> Appliquer
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Statistiques -->
        <div class="row mb-4 g-4">
            <div class="col-md-4">
                <div class="stat-card stat-revenu">
                    <i class="bi bi-arrow-down-circle"></i>
                    <h5>REVENUS</h5>
                    <p><?= number_format($total_revenu,0,',',' ') ?> F CFA</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card stat-depense">
                    <i class="bi bi-arrow-up-circle"></i>
                    <h5>DÉPENSES</h5>
                    <p><?= number_format($total_depense,0,',',' ') ?> F CFA</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card stat-solde">
                    <i class="bi bi-wallet2"></i>
                    <h5>SOLDE FINAL</h5>
                    <p><?= number_format($solde_final,0,',',' ') ?> F CFA</p>
                </div>
            </div>
        </div>

        <!-- Liste des opérations -->
        <div class="card">
            <div class="card-header">
                <i class="bi bi-list-ul me-2"></i> Historique des Opérations
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Libellé</th>
                                <th>Montant</th>
                                <th>Type</th>
                                <th>Source</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($operations as $op): ?>
                            <tr>
                                <td><?= date('d/m/Y',strtotime($op['date_operation'])) ?></td>
                                <td><?= htmlspecialchars($op['libelle']) ?></td>
                                <td><strong><?= number_format($op['montant'],0,',',' ') ?> F CFA</strong></td>
                                <td>
                                    <span class="badge rounded-pill <?= $op['type']=='revenu'?'badge-revenu':'badge-depense' ?>">
                                        <?= strtoupper($op['type']) ?>
                                    </span>
                                </td>
                                <td>
                                    <?php
                                    switch ($op['source']) {
                                        case 'mensualite': echo '<span class="badge bg-info">Mensualité</span>'; break;
                                        case 'reglement': echo '<span class="badge bg-warning">Lettre</span>'; break;
                                        default: echo '<span class="badge bg-secondary">Manuelle</span>';
                                    }
                                    ?>
                                </td>
                                <td>
                                    <?php if ($op['source'] == 'caisse' || $op['source'] == 'mensualite'): ?>
                                        <?php if ($_SESSION['user']['role'] == 'admin'): ?>
                                            <button class="btn btn-sm btn-warning" onclick='modifierOperation(<?= json_encode($op) ?>)'>
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button class="btn btn-sm btn-danger" onclick="supprimerOperation(<?= $op['id'] ?>, '<?= $op['source'] ?>')">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        <?php else: ?>
                                            <span class="text-muted">Accès limité</span>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
    function ajouterDepense(){
      Swal.fire({
        title: "Nouvelle Dépense",
        html: `
        <form id="depenseForm">
            <div class="mb-3">
                <label for="libelle" class="form-label">Libellé</label>
                <input id="libelle" class="form-control" placeholder="Description de la dépense" required>
            </div>
            <div class="mb-3">
                <label for="montant" class="form-label">Montant (F CFA)</label>
                <input id="montant" type="number" class="form-control" placeholder="Montant" required>
            </div>
            <div class="mb-3">
                <label for="date" class="form-label">Date</label>
                <input id="date" type="date" class="form-control" value="<?= date('Y-m-d') ?>" required>
            </div>
        </form>`,
        confirmButtonText: "<i class='bi bi-save me-1'></i> Enregistrer", 
        showCancelButton: true,
        cancelButtonText: "Annuler",
        focusConfirm: false,
        preConfirm: () => {
            const libelle = document.getElementById('libelle').value;
            const montant = document.getElementById('montant').value;
            const date = document.getElementById('date').value;
            
            if (!libelle || !montant || !date) {
                Swal.showValidationMessage("Veuillez remplir tous les champs");
                return false;
            }
            
            return fetch('', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: new URLSearchParams({
                    action: 'ajouter_depense',
                    libelle: libelle,
                    montant: montant,
                    date: date
                })
            }).then(r => r.text());
        }
      }).then(res => {
        if (res.isConfirmed) {
            Swal.fire({
                icon: 'success',
                title: 'Succès',
                text: 'Dépense ajoutée avec succès',
                timer: 1500,
                showConfirmButton: false
            }).then(() => location.reload());
        }
      });
    }

    function ajouterRevenu(){
      Swal.fire({
        title: "Nouveau Revenu",
        html: `
        <form id="revenuForm">
            <div class="mb-3">
                <label for="libelle" class="form-label">Libellé</label>
                <input id="libelle" class="form-control" placeholder="Description du revenu" required>
            </div>
            <div class="mb-3">
                <label for="montant" class="form-label">Montant (F CFA)</label>
                <input id="montant" type="number" class="form-control" placeholder="Montant" required>
            </div>
            <div class="mb-3">
                <label for="date" class="form-label">Date</label>
                <input id="date" type="date" class="form-control" value="<?= date('Y-m-d') ?>" required>
            </div>
        </form>`,
        confirmButtonText: "<i class='bi bi-save me-1'></i> Enregistrer", 
        showCancelButton: true,
        cancelButtonText: "Annuler",
        focusConfirm: false,
        preConfirm: () => {
            const libelle = document.getElementById('libelle').value;
            const montant = document.getElementById('montant').value;
            const date = document.getElementById('date').value;
            
            if (!libelle || !montant || !date) {
                Swal.showValidationMessage("Veuillez remplir tous les champs");
                return false;
            }
            
            return fetch('', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: new URLSearchParams({
                    action: 'ajouter_revenu',
                    libelle: libelle,
                    montant: montant,
                    date: date
                })
            }).then(r => r.text());
        }
      }).then(res => {
        if (res.isConfirmed) {
            Swal.fire({
                icon: 'success',
                title: 'Succès',
                text: 'Revenu ajouté avec succès',
                timer: 1500,
                showConfirmButton: false
            }).then(() => location.reload());
        }
      });
    }

    function modifierOperation(data){
      Swal.fire({
        title: "Modifier l'Opération",
        html: `
        <form id="editForm">
            <div class="mb-3">
                <label for="libelle" class="form-label">Libellé</label>
                <input id="libelle" class="form-control" value="${data.libelle}" required>
            </div>
            <div class="mb-3">
                <label for="montant" class="form-label">Montant (F CFA)</label>
                <input id="montant" type="number" class="form-control" value="${data.montant}" required>
            </div>
            <div class="mb-3">
                <label for="date" class="form-label">Date</label>
                <input id="date" type="date" class="form-control" value="${data.date_operation}" required>
            </div>
        </form>`,
        confirmButtonText: "<i class='bi bi-save me-1'></i> Enregistrer", 
        showCancelButton: true,
        cancelButtonText: "Annuler",
        focusConfirm: false,
        preConfirm: () => {
            const libelle = document.getElementById('libelle').value;
            const montant = document.getElementById('montant').value;
            const date = document.getElementById('date').value;
            
            if (!libelle || !montant || !date) {
                Swal.showValidationMessage("Veuillez remplir tous les champs");
                return false;
            }
            
            return fetch('', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: new URLSearchParams({
                    action: 'modifier_operation',
                    id: data.id,
                    libelle: libelle,
                    montant: montant,
                    date: date
                })
            }).then(r => r.text());
        }
      }).then(res => {
        if (res.isConfirmed) {
            Swal.fire({
                icon: 'success',
                title: 'Modifié',
                text: 'Opération mise à jour avec succès',
                timer: 1500,
                showConfirmButton: false
            }).then(() => location.reload());
        }
      });
    }

    function supprimerOperation(id, source){
      Swal.fire({
        title: 'Confirmation',
        text: "Êtes-vous sûr de vouloir supprimer cette opération ?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: '<i class="bi bi-trash me-1"></i> Oui, supprimer',
        cancelButtonText: 'Annuler'
      }).then((result) => {
        if (result.isConfirmed) {
            fetch('', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: new URLSearchParams({
                    action: 'supprimer_operation', 
                    id: id,
                    source: source
                })
            })
            .then(r => r.text())
            .then(() => {
                Swal.fire({
                    icon: 'success',
                    title: 'Supprimé',
                    text: 'Opération supprimée avec succès',
                    timer: 1500,
                    showConfirmButton: false
                }).then(() => location.reload());
            });
        }
      });
    }
    </script>

    <?php include 'includes/footer.php'; ?>
</body>
</html>