<?php
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';
header('Content-Type: text/html; charset=utf-8');

checkRole(['super_admin', 'school_admin', 'accountant']);

$schoolFilter = currentSchoolId();
$action = $_GET['action'] ?? 'list';
$id = isset($_GET['id']) ? (int)$_GET['id'] : null;
$error = '';

// ── Ajout / Modification ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_expense'])) {
    verifyCsrf();
    $description   = trim($_POST['description'] ?? '');
    $amount        = str_replace([' ', ','], ['', '.'], $_POST['amount'] ?? '0');
    $expenseDate   = $_POST['expense_date'] ?? date('Y-m-d');
    $category      = trim($_POST['category'] ?? '');
    $paymentMethod = $_POST['payment_method'] ?? '';
    $reference     = trim($_POST['reference_code'] ?? '');
    $schoolId      = $schoolFilter ?: (int)($_POST['school_id'] ?? 0);

    if (empty($description) || (float)$amount <= 0) {
        $error = 'Veuillez entrer une description et un montant valide.';
    } else {
        if ($id) {
            $whereSchool = $schoolFilter ? " AND school_id=?" : '';
            $params = [$schoolId, $description, (float)$amount, $expenseDate, $category ?: null, $paymentMethod ?: null, $reference ?: null, $id];
            if ($schoolFilter) $params[] = $schoolFilter;
            $pdo->prepare("UPDATE expenses SET school_id=?, description=?, amount=?, expense_date=?, category=?, payment_method=?, reference_code=? WHERE id=?" . $whereSchool)
                ->execute($params);
            $_SESSION['flash_toast'] = ['message'=>'Dépense modifiée.', 'type'=>'success'];
        } else {
            $pdo->prepare("INSERT INTO expenses (school_id, description, amount, expense_date, category, payment_method, reference_code) VALUES (?,?,?,?,?,?,?)")
                ->execute([$schoolId, $description, (float)$amount, $expenseDate, $category ?: null, $paymentMethod ?: null, $reference ?: null]);
            $_SESSION['flash_toast'] = ['message'=>'Dépense enregistrée.', 'type'=>'success'];
        }
        header('Location: expenses.php');
        exit;
    }
}

// ── Suppression ────────────────────────────────────────────────────────────────
if ($action === 'delete' && $id) {
    verifyCsrf();
    checkDeleteAllowed();
    if (!isSuperAdmin()) { $_SESSION['flash_toast'] = ['message'=>'Action réservée au super administrateur.', 'type'=>'error']; header('Location: expenses.php'); exit; }
    $pdo->prepare("DELETE FROM expenses WHERE id=?")->execute([$id]);
    $_SESSION['flash_toast'] = ['message'=>'Dépense supprimée.', 'type'=>'success'];
    header('Location: expenses.php'); exit;
}

// ── Chargement ─────────────────────────────────────────────────────────────────
$expense = null;
if ($id && $action === 'edit') {
    $whereSchool = $schoolFilter ? " AND school_id=?" : '';
    $stmt = $pdo->prepare("SELECT * FROM expenses WHERE id=?" . $whereSchool);
    $params = [$id];
    if ($schoolFilter) $params[] = $schoolFilter;
    $stmt->execute($params);
    $expense = $stmt->fetch();
}

$schools = [];
if (!$schoolFilter) {
    $schools = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();
}

// ── Liste ──────────────────────────────────────────────────────────────────────
$where = []; $params = [];
if ($schoolFilter) { $where[] = "school_id=?"; $params[] = $schoolFilter; }
$whereSql = count($where) ? " WHERE " . implode(' AND ', $where) : "";

$totalExpenses = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM expenses $whereSql");
$totalExpenses->execute($params);
$totalExpenses = (float)$totalExpenses->fetchColumn();

$expenses = $pdo->prepare("SELECT e.*, s.name AS school_name FROM expenses e LEFT JOIN schools s ON e.school_id=s.id $whereSql ORDER BY e.expense_date DESC, e.created_at DESC");
$expenses->execute($params);
$expenses = $expenses->fetchAll();
$__flash = $_SESSION['flash_toast'] ?? null;
unset($_SESSION['flash_toast']);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dépenses - Nukunu Mofiala</title>
<link rel="stylesheet" href="../assets/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root { --primary: #1F4E79; --accent: #2E75B6; --light: #D6E4F0; }
.prog-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:1.5rem; flex-wrap:wrap; gap:1rem; }
.prog-header h1 { font-family:Georgia,serif; color:var(--primary); font-size:1.6rem; }
.prog-header p { color:#666; font-size:.9rem; }
.table-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); overflow:hidden; margin-bottom:1.5rem; }
.table-card .tc-header { padding:1rem 1.5rem; border-bottom:1px solid #E5E7EB; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:.5rem; }
.table-card .tc-title { font-family:Georgia,serif; color:var(--primary); font-size:1.05rem; }
.prog-table { width:100%; border-collapse:collapse; }
.prog-table thead { background:var(--primary); color:white; }
.prog-table th { padding:.6rem .8rem; text-align:left; font-weight:600; font-size:.74rem; text-transform:uppercase; letter-spacing:.4px; white-space:nowrap; }
.prog-table td { padding:.55rem .8rem; border-bottom:1px solid #E5E7EB; font-size:.82rem; vertical-align:middle; }
.prog-table tbody tr:hover { background:#F9FAFB; }
.btn { display:inline-flex; align-items:center; gap:6px; padding:.5rem 1.1rem; border:none; border-radius:6px; font-size:.82rem; font-weight:600; cursor:pointer; transition:all .2s; text-decoration:none; }
.btn-primary { background:var(--primary); color:white; }
.btn-primary:hover { background:#163a5c; }
.btn-light { background:#E5E7EB; color:#374151; }
.btn-light:hover { background:#D1D5DB; }
.btn-success { background:#10B981; color:white; }
.btn-success:hover { background:#059669; }
.btn-danger { background:#E53E3E; color:white; }
.btn-danger:hover { background:#C53030; }
.empty-state { text-align:center; padding:3rem 1rem; color:#9CA3AF; }
.empty-state i { font-size:2.5rem; display:block; margin-bottom:.75rem; color:#CBD5E1; }
.form-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); padding:1.5rem 2rem; margin-bottom:1.5rem; max-width:640px; }
.form-card h2 { font-family:Georgia,serif; color:var(--primary); font-size:1.15rem; margin-bottom:1.25rem; display:flex; align-items:center; gap:.5rem; }
.form-row { display:flex; gap:1.25rem; flex-wrap:wrap; margin-bottom:1rem; }
.form-row .form-group { flex:1; min-width:180px; }
.form-group { margin-bottom:1rem; }
.form-group label { display:block; font-weight:600; color:var(--primary); font-size:.8rem; margin-bottom:4px; }
.form-group select, .form-group input, .form-group textarea { width:100%; padding:.55rem .75rem; border:1px solid #D1D5DB; border-radius:6px; font-size:.85rem; background:white; box-sizing:border-box; }
.form-group select:focus, .form-group input:focus, .form-group textarea:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(46,117,182,0.15); }
.toast-container { position:fixed; bottom:30px; right:30px; z-index:2000; display:flex; flex-direction:column; gap:10px; }
.toast { background:white; padding:12px 18px; border-radius:8px; box-shadow:0 4px 20px rgba(0,0,0,0.15); display:flex; align-items:center; gap:10px; animation:slideIn .3s ease; border-left:4px solid var(--primary); font-size:.9rem; }
.toast-success { border-left-color:#10B981; }
.toast-error { border-left-color:#EF4444; }
@keyframes slideIn { from{transform:translateX(100%);opacity:0;} to{transform:translateX(0);opacity:1;} }
@media (max-width:768px) {
  .prog-header { flex-direction:column; align-items:flex-start; }
  .form-row { flex-direction:column; }
  .form-row .form-group { min-width:100%; }
  .form-card { padding:1rem; }
  .table-card .tc-header { flex-direction:column; align-items:flex-start; }
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-shopping-cart"></i> Gestion des dépenses'; include '../includes/topbar.php'; ?>

        <?php if ($error): ?><div class="error-message" style="margin-bottom:1rem;"><?= e($error) ?></div><?php endif; ?>

        <!-- ═══ Header ═══ -->
        <div class="prog-header">
            <div>
                <h1><i class="fas fa-shopping-cart" style="color:#E53E3E;"></i> Gestion des dépenses</h1>
                <p>Suivez et gérez les dépenses de l'établissement</p>
            </div>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;align-items:center;">
                <a href="?action=add" class="btn btn-danger"><i class="fas fa-plus"></i> Nouvelle dépense</a>
                <span style="font-size:.9rem;color:#718096;">Total dépenses : <strong style="color:#E53E3E;"><?= formatAmount($totalExpenses) ?></strong></span>
            </div>
        </div>

        <?php if ($action === 'add' || ($action === 'edit' && $expense)): ?>
        <!-- ═══ Formulaire ═══ -->
        <div class="form-card">
            <h2><i class="fas fa-<?= $expense ? 'edit' : 'plus-circle' ?>"></i> <?= $expense ? 'Modifier' : 'Enregistrer' ?> une dépense</h2>
            <form method="POST">
                <?= csrfField() ?>
                <?php if (!$schoolFilter): ?>
                <div class="form-row">
                    <div class="form-group">
                        <label>École</label>
                        <select name="school_id" required>
                            <option value="">Choisir...</option>
                            <?php foreach ($schools as $sc): ?>
                            <option value="<?=$sc['id']?>" <?=($expense['school_id']??'')==$sc['id']?'selected':''?>><?=e($sc['name'])?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <?php endif; ?>
                <div class="form-group">
                    <label>Description</label>
                    <textarea name="description" required rows="2"><?=e($expense['description'] ?? '')?></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Montant (<?=CURRENCY?>)</label>
                        <input type="number" name="amount" required min="1" step="1" value="<?=e($expense['amount'] ?? '')?>">
                    </div>
                    <div class="form-group">
                        <label>Date</label>
                        <input type="date" name="expense_date" value="<?=e($expense['expense_date'] ?? date('Y-m-d'))?>">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Catégorie</label>
                        <select name="category">
                            <option value="">— Choisir —</option>
                            <?php
                            $cats = ['Fournitures','Électricité','Eau','Salaire','Entretien','Transport','Communication','Équipement','Autre'];
                            $curCat = $expense['category'] ?? '';
                            foreach ($cats as $c): ?>
                            <option value="<?=$c?>" <?=$curCat===$c?'selected':''?>><?=$c?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Mode de paiement</label>
                        <select name="payment_method">
                            <option value="">— Choisir —</option>
                            <?php foreach (['Espèces','Virement','Mobile Money','Carte','Chèque'] as $m): ?>
                            <option value="<?=$m?>" <?=($expense['payment_method']??'')===$m?'selected':''?>><?=$m?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>Référence (optionnel)</label>
                    <input type="text" name="reference_code" value="<?=e($expense['reference_code'] ?? '')?>">
                </div>
                <div style="display:flex;gap:.75rem;">
                    <button type="submit" name="save_expense" class="btn btn-primary"><i class="fas fa-save"></i> <?=$expense?'Modifier':'Enregistrer'?></button>
                    <a href="expenses.php" class="btn btn-light">Annuler</a>
                </div>
            </form>
        </div>

        <?php else: ?>
        <!-- ═══ Tableau des dépenses ═══ -->
        <div class="table-card">
            <div class="tc-header">
                <div class="tc-title"><i class="fas fa-list"></i> Liste des dépenses</div>
                <span style="color:#718096;font-size:.82rem;"><?= count($expenses) ?> dépense(s)</span>
            </div>
            <div style="overflow-x:auto;">
            <table class="prog-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Description</th>
                        <th>Catégorie</th>
                        <th style="text-align:right">Montant</th>
                        <th>Mode</th>
                        <th>Référence</th>
                        <?php if (!$schoolFilter): ?><th>École</th><?php endif; ?>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($expenses as $ex): ?>
                    <tr>
                        <td><?=formatDate($ex['expense_date'])?></td>
                        <td><?=e($ex['description'])?></td>
                        <td><span style="background:#fefcbf;color:#744210;padding:2px 8px;border-radius:10px;font-size:.78rem;font-weight:600;"><?=e($ex['category'] ?? '—')?></span></td>
                        <td style="text-align:right;font-weight:700;color:#E53E3E;"><?=formatAmount($ex['amount'])?></td>
                        <td><?=e($ex['payment_method'] ?? '-')?></td>
                        <td><?=e($ex['reference_code'] ?? '-')?></td>
                        <?php if (!$schoolFilter): ?><td><?=e($ex['school_name'] ?? '-')?></td><?php endif; ?>
                        <td>
                            <div style="display:flex;gap:.3rem;">
                            <a href="?action=edit&id=<?=$ex['id']?>" class="btn btn-light" style="padding:.35rem .55rem;font-size:.75rem;" title="Modifier"><i class="fas fa-edit"></i></a>
                            <?php if (isSuperAdmin()): ?>
                            <form method="POST" action="?action=delete&id=<?=$ex['id']?>" style="display:inline" onsubmit="return confirm('Supprimer cette dépense ?')">
                                <?=csrfField()?>
                                <button type="submit" class="btn btn-danger" style="padding:.35rem .55rem;font-size:.75rem;" title="Supprimer"><i class="fas fa-trash"></i></button>
                            </form>
                            <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($expenses)): ?>
                    <tr><td colspan="<?= $schoolFilter ? 7 : 8 ?>" style="text-align:center;padding:2rem;color:#9CA3AF;">Aucune dépense enregistrée</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>

<script>
function showToast(msg,type){var c=document.getElementById('toastContainer');var t=document.createElement('div');t.className='toast toast-'+(type==='success'?'success':'error');t.innerHTML='<span>'+(type==='success'?'&#x2705;':'&#x274C;')+'</span><span>'+msg+'</span>';c.appendChild(t);setTimeout(function(){t.remove();},4000);}
<?php if ($__flash ?? false): ?>
document.addEventListener('DOMContentLoaded',function(){showToast(<?=json_encode($__flash['message'])?>,<?=json_encode($__flash['type'])?>);});
<?php endif; ?>
</script>
<script src="../assets/js/main.js"></script>
</body>
</html>
