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

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

// Delete
if ($action === 'delete' && $id) {
    $db->prepare("DELETE FROM depenses WHERE id=?")->execute([$id]);
    logAction($_SESSION['user_id'], 'depense_delete', "Dépense #$id supprimée");
    flash('success', 'Dépense supprimée.');
    redirect('/depenses.php');
}

// Save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $editId = intval($_POST['id'] ?? 0);
    $data = [
        intval($_POST['programme_id'] ?? 0) ?: null,
        $_POST['categorie'] ?? '',
        $_POST['description'] ?? '',
        floatval($_POST['montant'] ?? 0),
        $_POST['date_depense'] ?? date('Y-m-d'),
        $_POST['fournisseur'] ?? '',
        $_POST['reference'] ?? '',
        $_POST['notes'] ?? '',
    ];

    if ($editId) {
        $data[] = $editId;
        $db->prepare("UPDATE depenses SET programme_id=?,categorie=?,description=?,montant=?,date_depense=?,fournisseur=?,reference=?,notes=? WHERE id=?")->execute($data);
        flash('success', 'Dépense modifiée.');
    } else {
        $data[] = $_SESSION['user_id'];
        $db->prepare("INSERT INTO depenses (programme_id,categorie,description,montant,date_depense,fournisseur,reference,notes,created_by) VALUES (?,?,?,?,?,?,?,?,?)")->execute($data);
        flash('success', 'Dépense ajoutée.');
    }
    logAction($_SESSION['user_id'], 'depense_save', "Dépense enregistrée");
    redirect('/depenses.php');
}

// Form
if ($action === 'add' || $action === 'edit') {
    $depense = null;
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM depenses WHERE id=?");
        $stmt->execute([$id]);
        $depense = $stmt->fetch();
    }
    $programmes = $db->query("SELECT id, nom, type FROM programmes ORDER BY date_depart DESC")->fetchAll();
    $categories = ['hotel'=>'Hôtel','vol'=>'Vol / Billet avion','visa'=>'Frais visa','transport'=>'Transport interne','commission'=>'Commission','restauration'=>'Restauration','assurance'=>'Assurance','autre'=>'Autre'];
?>
    <div class="d-flex justify-content-between mb-4">
        <a href="<?= APP_URL ?>/depenses.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-wallet2 me-2"></i><?= $depense ? 'Modifier la dépense' : 'Nouvelle dépense' ?></div>
        <div class="card-body p-4">
            <form method="POST">
                <input type="hidden" name="id" value="<?= $depense['id'] ?? '' ?>">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Programme</label>
                        <select name="programme_id" class="form-select select2">
                            <option value="">-- Général --</option>
                            <?php foreach ($programmes as $p): ?>
                                <option value="<?= $p['id'] ?>" <?= ($depense['programme_id'] ?? '')==$p['id']?'selected':'' ?>><?= sanitize($p['nom'].' ['.ucfirst($p['type']).']') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Catégorie *</label>
                        <select name="categorie" class="form-select" required>
                            <?php foreach ($categories as $k=>$v): ?>
                                <option value="<?= $k ?>" <?= ($depense['categorie'] ?? '')==$k?'selected':'' ?>><?= $v ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Montant (MAD) *</label>
                        <input type="number" step="0.01" name="montant" class="form-control" value="<?= $depense['montant'] ?? '' ?>" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Description</label>
                        <input type="text" name="description" class="form-control" value="<?= sanitize($depense['description'] ?? '') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Fournisseur</label>
                        <input type="text" name="fournisseur" class="form-control" value="<?= sanitize($depense['fournisseur'] ?? '') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Date</label>
                        <input type="date" name="date_depense" class="form-control" value="<?= $depense['date_depense'] ?? date('Y-m-d') ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Référence</label>
                        <input type="text" name="reference" class="form-control" value="<?= sanitize($depense['reference'] ?? '') ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Notes</label>
                        <input type="text" name="notes" class="form-control" value="<?= sanitize($depense['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 ?>/depenses.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>
<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

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

$where = "WHERE 1=1";
$params = [];
if ($search) { $where .= " AND (d.description LIKE ? OR d.fournisseur LIKE ? OR d.reference LIKE ?)"; $s="%$search%"; $params=[$s,$s,$s]; }
if ($catFilter) { $where .= " AND d.categorie=?"; $params[] = $catFilter; }

$total = $db->prepare("SELECT COUNT(*) FROM depenses d $where");
$total->execute($params);
$pagination = paginate($total->fetchColumn(), 15, $page);

$stmt = $db->prepare("SELECT d.*, p.nom as programme_nom FROM depenses d LEFT JOIN programmes p ON d.programme_id=p.id $where ORDER BY d.date_depense DESC LIMIT {$pagination['per_page']} OFFSET {$pagination['offset']}");
$stmt->execute($params);
$depenses = $stmt->fetchAll();

$totalMontant = $db->prepare("SELECT COALESCE(SUM(d.montant),0) FROM depenses d $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="categorie" class="form-select" style="width:160px;">
            <option value="">Toutes catégories</option>
            <option value="hotel" <?= $catFilter=='hotel'?'selected':'' ?>>Hôtel</option>
            <option value="vol" <?= $catFilter=='vol'?'selected':'' ?>>Vol</option>
            <option value="visa" <?= $catFilter=='visa'?'selected':'' ?>>Visa</option>
            <option value="transport" <?= $catFilter=='transport'?'selected':'' ?>>Transport</option>
            <option value="commission" <?= $catFilter=='commission'?'selected':'' ?>>Commission</option>
            <option value="autre" <?= $catFilter=='autre'?'selected':'' ?>>Autre</option>
        </select>
        <button class="btn btn-outline-primary">Filtrer</button>
    </form>
    <div class="d-flex gap-2 align-items-center">
        <span class="badge bg-danger fs-6 py-2 px-3">Total: <?= formatMoney($totalMontant) ?></span>
        <a href="<?= APP_URL ?>/depenses.php?action=add" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Nouvelle dépense</a>
    </div>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover">
            <thead><tr><th>Date</th><th>Catégorie</th><th>Description</th><th>Programme</th><th>Fournisseur</th><th>Montant</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($depenses as $d): 
                $catIcons = ['hotel'=>'bi-building','vol'=>'bi-airplane','visa'=>'bi-passport','transport'=>'bi-bus-front','commission'=>'bi-percent','autre'=>'bi-tag'];
            ?>
                <tr>
                    <td><?= formatDate($d['date_depense']) ?></td>
                    <td><i class="bi <?= $catIcons[$d['categorie']] ?? 'bi-tag' ?> me-1"></i><?= ucfirst($d['categorie']) ?></td>
                    <td><?= sanitize($d['description'] ?: '-') ?></td>
                    <td><small><?= sanitize($d['programme_nom'] ?: 'Général') ?></small></td>
                    <td><?= sanitize($d['fournisseur'] ?: '-') ?></td>
                    <td class="fw-bold text-danger"><?= formatMoney($d['montant']) ?></td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="<?= APP_URL ?>/depenses.php?action=edit&id=<?= $d['id'] ?>" class="btn btn-outline-warning"><i class="bi bi-pencil"></i></a>
                            <a href="<?= APP_URL ?>/depenses.php?action=delete&id=<?= $d['id'] ?>" class="btn btn-outline-danger" onclick="return confirmDelete()"><i class="bi bi-trash"></i></a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($depenses)): ?><tr><td colspan="7" class="text-center text-muted py-4">Aucune dépense</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card-footer">
        <?= renderPagination($pagination, APP_URL.'/depenses.php?search='.urlencode($search).'&categorie='.urlencode($catFilter)) ?>
    </div>
</div>

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