<?php
// Déplacer cette ligne tout en haut, avant tout code HTML
if (session_status() === PHP_SESSION_NONE) @session_start();

// Récupérer la date du jour au format Y-m-d
$today = date('Y-m-d');

if (isset($_SESSION['flash'])) {
    $flashType = $_SESSION['flash']['type'];
    $flashMessage = $_SESSION['flash']['message'];
    unset($_SESSION['flash']);
    
    $alertClass = '';
    $icon = '';
    
    switch ($flashType) {
        case 'success':
            $alertClass = 'alert-success';
            $icon = 'fa-check-circle';
            break;
        case 'danger':
            $alertClass = 'alert-danger';
            $icon = 'fa-exclamation-circle';
            break;
        case 'warning':
            $alertClass = 'alert-warning';
            $icon = 'fa-exclamation-triangle';
            break;
        default:
            $alertClass = 'alert-info';
            $icon = 'fa-info-circle';
    }
}

$id_utilisateur = $_SESSION['user']['id_utilisateur'];
?>

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Gestion des dépenses - BeWise</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="icon" href="favicon.ico" type="../image/x-icon" />
  <!-- END META SECTION -->
  <!-- CSS INCLUDE -->        
  <link rel="stylesheet" type="text/css" id="theme" href="../css/theme-default.css"/>
  <!-- EOF CSS INCLUDE --> 
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

  
  <style>
    body {
      margin: 0;
      font-family: 'Segoe UI', sans-serif;
      background-color: #f4f6f8;
      color: #333;
    }

    h2 {
      background-color: #dc3545;
      color: white;
      padding: 20px;
      margin: 0;
      text-align: center;
      font-size: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
    }

    .card-container {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      gap: 20px;
      padding: 30px;
    }

    .card {
      background-color: white;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
      padding: 25px;
      width: 100%;
      max-width: 1200px;
    }

    /* Notification améliorée */
    .notification {
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 15px 25px;
      border-radius: 8px;
      color: white;
      z-index: 1000;
      display: flex;
      align-items: center;
      gap: 12px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      opacity: 0;
      transition: opacity 0.5s ease-in-out;
    }

    .notification.show {
      opacity: 1;
    }

    .notification-success {
      background-color: #28a745;
      border-left: 5px solid #218838;
    }

    .notification-error {
      background-color: #e74c3c;
      border-left: 5px solid #c82333;
    }

    .notification-warning {
      background-color: #ffc107;
      border-left: 5px solid #e0a800;
      color: #212529;
    }

    .notification-info {
      background-color: #17a2b8;
      border-left: 5px solid #138496;
    }

    .notification i {
      font-size: 20px;
    }

    /* Formulaires améliorés */
    .form-group {
      margin-bottom: 20px;
      position: relative;
    }

    .form-group label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: #555;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .form-group input,
    .form-group select,
    .form-group textarea {
      width: 100%;
      padding: 12px 15px;
      border: 1px solid #ddd;
      border-radius: 8px;
      font-size: 16px;
      transition: all 0.3s;
      background-color: #f8f9fa;
    }

    .form-group input:focus,
    .form-group select:focus,
    .form-group textarea:focus {
      border-color: #dc3545;
      outline: none;
      box-shadow: 0 0 0 3px rgba(220, 53, 69, 0.2);
      background-color: white;
    }

    /* Tableau amélioré */
    .table-responsive {
      overflow-x: auto;
      margin-top: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }
    
    table {
      width: 100%;
      border-collapse: separate;
      border-spacing: 0;
      margin: 20px 0;
    }

    th, td {
      padding: 14px 16px;
      text-align: left;
      border-bottom: 1px solid #e0e0e0;
    }

    th {
      background-color: #dc3545;
      color: white;
      font-weight: 600;
      position: sticky;
      top: 0;
    }

    /* Styles pour les catégories */
    .categorie-Vie_courante_et_besoins_essentiels {
      background-color: #e3f2fd;
    }
    .categorie-Activite_professionnelle_ou_business {
      background-color: #e8f5e9;
    }
    .categorie-Engagements_financiers {
      background-color: #fff3e0;
    }
    .categorie-Depenses_sociales_ou_personnelles {
      background-color: #f3e5f5;
    }
    .categorie-Projets_et_investissements {
      background-color: #e0f7fa;
    }
    .categorie-Institutionnel_et_reglementaire {
      background-color: #ffebee;
    }

    tr:hover td {
      background-color: #f1f1f1 !important;
    }
  
    body {
      margin: 0;
      font-family: 'Segoe UI', sans-serif;
      background-color: #f4f6f8;
      color: #333;
    }

    h2 {
      background-color: #dc3545;
      color: white;
      padding: 20px;
      margin: 0;
      text-align: center;
      font-size: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
    }

    .card-container {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      gap: 20px;
      padding: 30px;
    }

    .card {
      background-color: white;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
      padding: 25px;
      width: 100%;
      max-width: 1200px;
    }

    /* Notification améliorée */
    .notification {
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 15px 25px;
      border-radius: 8px;
      color: white;
      z-index: 1000;
      display: flex;
      align-items: center;
      gap: 12px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      transform: translateX(150%);
      transition: transform 0.4s ease-out, opacity 0.4s ease-out;
      opacity: 0;
    }

    .notification.show {
      transform: translateX(0);
      opacity: 1;
    }

    .notification.hide {
      transform: translateX(150%);
      opacity: 0;
    }

    .notification-success {
      background-color: #28a745;
      border-left: 5px solid #218838;
    }

    .notification-error {
      background-color: #e74c3c;
      border-left: 5px solid #c82333;
    }

    .notification-warning {
      background-color: #ffc107;
      border-left: 5px solid #e0a800;
      color: #212529;
    }

    .notification-info {
      background-color: #17a2b8;
      border-left: 5px solid #138496;
    }

    .notification i {
      font-size: 20px;
    }

    /* Formulaires améliorés */
    .form-group {
      margin-bottom: 20px;
      position: relative;
    }

    .form-group label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: #555;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .form-group input,
    .form-group select,
    .form-group textarea {
      width: 100%;
      padding: 12px 15px;
      border: 1px solid #ddd;
      border-radius: 8px;
      font-size: 16px;
      transition: all 0.3s;
      background-color: #f8f9fa;
    }

    .form-group input::placeholder,
    .form-group select:invalid,
    .form-group textarea::placeholder {
      color: #6c757d;
      opacity: 0.7;
    }

    .form-group input:focus,
    .form-group select:focus,
    .form-group textarea:focus {
      border-color: #dc3545;
      outline: none;
      box-shadow: 0 0 0 3px rgba(220, 53, 69, 0.2);
      background-color: white;
    }

    .form-group textarea {
      min-height: 100px;
      resize: vertical;
    }

    /* Tableau amélioré */
    .table-responsive {
      overflow-x: auto;
      margin-top: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }
    
    table {
      width: 100%;
      border-collapse: separate;
      border-spacing: 0;
      margin: 20px 0;
    }

    th, td {
      padding: 14px 16px;
      text-align: left;
      border-bottom: 1px solid #e0e0e0;
    }

    th {
      background-color: #dc3545;
      color: white;
      font-weight: 600;
      position: sticky;
      top: 0;
    }

    tr:nth-child(even) {
      background-color: #f9f9f9;
    }

    tr:hover {
      background-color: #f1f1f1;
    }

    /* Autres styles existants améliorés */
    .btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      text-decoration: none;
      color: white;
      padding: 12px 20px;
      border-radius: 8px;
      font-weight: bold;
      border: none;
      cursor: pointer;
      font-size: 16px;
      transition: all 0.3s;
      margin-top: 10px;
    }

    .btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    }

    .btn-primary {
      background-color: #dc3545;
    }

    .btn-primary:hover {
      background-color: #c82333;
    }

    .btn-secondary {
      background-color: #6c757d;
    }

    .btn-secondary:hover {
      background-color: #5a6268;
    }

    .btn-danger {
      background-color: #dc3545;
    }

    .btn-danger:hover {
      background-color: #c82333;
    }

    .btn-sm {
      padding: 8px 12px;
      font-size: 14px;
    }

    .btn-group {
      display: flex;
      gap: 15px;
      margin-top: 25px;
    }

    .actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }

    .badge {
      display: inline-block;
      padding: 5px 10px;
      border-radius: 50px;
      font-size: 12px;
      font-weight: 500;
    }

    .badge-fixe {
      background-color: #e6f7ff;
      color: #0066cc;
      border: 1px solid #b3e0ff;
    }

    .badge-variable {
      background-color: #fff7e6;
      color: #cc8800;
      border: 1px solid #ffdd99;
    }

    .badge-prevue {
      background-color: #fff2e6;
      color: #cc5500;
      border: 1px solid #ffbb99;
    }

    .badge-realisee {
      background-color: #e6ffed;
      color: #00aa44;
      border: 1px solid #99ffbb;
    }

    .filter-controls {
      display: flex;
      gap: 20px;
      margin-bottom: 20px;
      flex-wrap: wrap;
    }

    .filter-group {
      flex: 1;
      min-width: 200px;
    }

    .filter-group label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: #555;
    }

    .filter-group input,
    .filter-group select {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid #ddd;
      border-radius: 8px;
      background-color: #f8f9fa;
    }

    .no-results {
      text-align: center;
      padding: 20px;
      color: #6c757d;
      font-style: italic;
    }

    footer {
      margin: 30px 0;
      text-align: center;
      color: #888;
      font-size: 14px;
    }

    /* Styles pour les sélecteurs avec icônes */
    select {
      -webkit-appearance: none;
      -moz-appearance: none;
      appearance: none;
      background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
      background-repeat: no-repeat;
      background-position: right 10px center;
      background-size: 15px;
      padding-right: 30px !important;
    }

    @media (max-width: 768px) {
      .card {
        padding: 15px;
      }
      
      .btn-group {
        flex-direction: column;
      }
      
      .filter-controls {
        flex-direction: column;
        gap: 10px;
      }
      
      .filter-group {
        width: 100%;
      }
      
      .actions {
        flex-direction: column;
        gap: 5px;
      }
      
      th, td {
        padding: 8px 10px;
        font-size: 14px;
      }
    }
    
    .alert {
      display: flex;
      align-items: center;
      gap: 10px;
      border: 1px solid transparent;
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
    }
    .alert-success {
      color: #155724;
      background-color: #d4edda;
      border-color: #c3e6cb;
    }
    .alert-danger {
      color: #721c24;
      background-color: #f8d7da;
      border-color: #f5c6cb;
    }
    .alert-warning {
      color: #856404;
      background-color: #fff3cd;
      border-color: #ffeeba;
    }
    .alert-info {
      color: #0c5460;
      background-color: #d1ecf1;
      border-color: #bee5eb;
    }

    /* Tooltip pour les champs de formulaire */
    [data-tooltip] {
      position: relative;
      cursor: pointer;
    }
    
    [data-tooltip]:hover::after {
      content: attr(data-tooltip);
      position: absolute;
      bottom: 100%;
      left: 50%;
      transform: translateX(-50%);
      background: #333;
      color: #fff;
      padding: 5px 10px;
      border-radius: 4px;
      font-size: 14px;
      white-space: nowrap;
      z-index: 100;
      margin-bottom: 5px;
    }
    
    [data-tooltip]:hover::before {
      content: '';
      position: absolute;
      bottom: 100%;
      left: 50%;
      transform: translateX(-50%);
      border-width: 5px;
      border-style: solid;
      border-color: #333 transparent transparent transparent;
      z-index: 100;
      margin-bottom: -5px;
    }
        
     /* Ajout des couleurs par catégorie */
        .categorie-Vie_courante_et_besoins_essentiels {
          background-color: #e3f2fd;
          border-left: 4px solid #2196f3;
        }
        .categorie-Activite_professionnelle_ou_business {
          background-color: #e8f5e9;
          border-left: 4px solid #4caf50;
        }
        .categorie-Engagements_financiers {
          background-color: #fff3e0;
          border-left: 4px solid #ff9800;
        }
        .categorie-Depenses_sociales_ou_personnelles {
          background-color: #f3e5f5;
          border-left: 4px solid #9c27b0;
        }
        .categorie-Projets_et_investissements {
          background-color: #e0f7fa;
          border-left: 4px solid #00bcd4;
        }
        .categorie-Institutionnel_et_reglementaire {
          background-color: #ffebee;
          border-left: 4px solid #f44336;
        }
    
        /* Surbrillance au survol */
        tr:hover td {
          background-color: #f5f5f5 !important;
        }
        
     select.form-control option {
        padding: 5px;
    }
    /* Optionnel : pour les navigateurs supportant ::before dans les options */
    select.form-control option:before {
        font-family: 'Font Awesome 5 Free';
        font-weight: 900;
        margin-right: 10px;
    } 
  </style>
</head>
<body>

 <?php if (isset($flashType)): ?>
    <div class="notification notification-<?= $flashType ?> show" id="flashNotification">
      <i class="fas <?= $icon ?>"></i>
      <span><?= $flashMessage ?></span>
    </div>
  <?php endif; ?>

  <h2><i class="fas fa-money-bill-wave"></i> Gestion des dépenses</h2>

  <div class="card-container">
    <div class="card">
     <div>
      <h3 style="color: #dc3545; margin-bottom: 20px;"><i class="fas fa-plus-circle"></i> Ajouter une dépense</h3>
      
      <?php if (isset($alertClass)): ?>
        <div class="alert <?= $alertClass ?>">
          <i class="fas <?= $icon ?>"></i>
          <?= $flashMessage ?>
        </div>
      <?php endif; ?>
      </div>
      
      <form method="POST" action="../index.php/store_depense">
        <input type="hidden" name="id_faiseur" value="<?= $id_faiseur ?>">
        
        <div class="form-group">
          <label><i class="fas fa-tag"></i> Libellé :</label>
          <input type="text" name="libelles_depenses" required placeholder="Ex: Loyer mensuel, Courses alimentaires..." title="Nom descriptif de la dépense">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-list"></i> Catégorie :</label>
          <select name="categories" required title="Catégorie principale de la dépense">
            <option value="" disabled selected>Sélectionnez une catégorie</option>
            <option value="Vie_courante_et_besoins_essentiels">Vie courante et besoins essentiels</option>
            <option value="Activite_professionnelle_ou_business">Activité professionnelle ou business</option>
            <option value="Engagements_financiers">Engagements financiers</option>
            <option value="Depenses_sociales_ou_personnelles">Dépenses sociales ou personnelles</option>
            <option value="Projets_et_investissements">Projets et investissements</option>
            <option value="Institutionnel_et_reglementaire">Institutionnel et réglementaire</option>
          </select>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-list-ol"></i> Sous-catégorie :</label>
          <select name="sous_categories" required title="Sous-catégorie plus précise">
            <option value="" disabled selected>Sélectionnez une sous-catégorie</option>
            <?php
              $sousCats = [
                'Logement', 'Alimentation', 'Transport', 'Santé', 'Éducation',
                'Fournitures pro', 'Communication', 'Déplacement pro', 'Salaires',
                'Remboursement dette', 'Versement épargne', 'Assurance', 'Loisirs',
                'Cadeaux', 'Cérémonie', 'Habits', 'Immobilier', 'Inversement',
                'Maintenance', 'Impôt taxes', 'Frais administratifs', 'Cotisation',
                'Energie électrique', 'Autre 2', 'Autre 3', 'Autre 4', 'Autre 5',
                'Autre 6', 'Autre 7', 'Autre 8', 'Autre 9'
              ];
              foreach ($sousCats as $sc) {
                echo "<option value=\"$sc\">$sc</option>";
              }
            ?>
          </select>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-cog"></i> Type de dépense :</label>
          <select name="type_depense" required title="Type de dépense (fixe ou variable)">
            <option value="" disabled selected>Sélectionnez un type</option>
            <option value="Fixe">Fixe</option>
            <option value="Variable">Variable</option>
          </select>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-calendar-alt"></i> Périodicité :</label>
          <select name="periodicite" required title="Fréquence de la dépense">
            <option value="" disabled selected>Sélectionnez une périodicité</option>
            <option value="Journalière">Journalière</option>
            <option value="Hebdomadaire">Hebdomadaire</option>
            <option value="Mensuelle">Mensuelle</option>
            <option value="Trimestrielle">Trimestrielle</option>
            <option value="Semestrielle">Semestrielle</option>
            <option value="Annuelle">Annuelle</option>
            <option value="Alternative">Alternative</option>
          </select>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-coins"></i> Montant périodique :</label>
          <input type="number" name="montant_periodique" step="0.01" required 
                 placeholder="Ex: 50000" title="Montant pour chaque période">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-calculator"></i> Montant annuel estimatif :</label>
          <input type="number" name="montant_annuel_estimatif" step="0.01"
                 placeholder="Calculé automatiquement si vide" title="Estimation annuelle">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-calendar-day"></i> Date prévue :</label>
          <input type="date" name="date_prevu_depense" required 
                 title="Date prévue pour cette dépense" value="<?= $today ?>">
        </div>

        <div class="form-group">
          <label><i class="fas fa-calendar-day"></i> Date écheance :</label>
          <input type="date" name="date_echeance" required 
                 title="Date d'échéance de paiement" value="<?= $today ?>">
        </div>

        <div class="form-group">
          <label><i class="fas fa-info-circle"></i> Statut :</label>
          <select name="statut_depense" required title="Statut actuel de la dépense">
            <option value="" disabled selected>Sélectionnez un statut</option>
            <option value="Prévue">Prévue</option>
            <option value="Réalisée">Réalisée</option>
          </select>
        </div>
        
        <div class="form-group">
            <label><i class="fas fa-credit-card"></i> Mode de paiement :</label>
            <select name="mode_paiement" title="Sélectionnez le mode de paiement utilisé" required>
                <option value="">-- Sélectionnez un mode de paiement --</option>
                <option value="Espèces">💰 Espèces</option>
                <option value="Carte bancaire">💳 Carte bancaire (CB/Visa/Mastercard)</option>
                <option value="Chèque">📝 Chèque</option>
                <option value="Virement">↔️ Virement bancaire</option>
                <option value="Prélèvement">🔄 Prélèvement automatique</option>
                <option value="Mobile Payment">📱 Paiement mobile (Paypal, Lydia...)</option>
                <option value="Crypto">🪙 Cryptomonnaie</option>
                <option value="Carte cadeau">🎁 Carte cadeau</option>
                <option value="Virement instantané">⚡ Virement instantané</option>
                <option value="Portefeuille électronique">👛 Portefeuille électronique</option>
                <option value="Autre">❓ Autre moyen</option>
            </select>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-user"></i> Bénéficiaire :</label>
          <select name="id_receveur" title="Personne ou entité recevant le paiement">
            <option value="" disabled selected>Sélectionnez un bénéficiaire</option>
            <?php foreach ($utilisateurs as $u): ?>
              <option value="<?= $u['id_utilisateur'] ?>">
                <?= htmlspecialchars($u['nom'] . ' ' . $u['prenom']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-chart-line"></i> Impact budgétaire :</label>
          <select name="impact_budgetaire" required title="Impact sur votre budget global">
            <option value="" disabled selected>Sélectionnez un impact</option>
            <option value="Fort">Fort</option>
            <option value="Moyen">Moyen</option>
            <option value="Faible">Faible</option>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-user-check"></i> Responsable validation :</label>
          <select name="responsable_validation" title="Personne responsable de valider cette dépense">
            <option value="" disabled selected>Sélectionnez un responsable</option>
            <?php foreach ($utilisateurs as $u): ?>
              <option value="<?= $u['id_utilisateur'] ?>">
                <?= htmlspecialchars($u['nom'] . ' ' . $u['prenom']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-align-left"></i> Description :</label>
          <textarea name="description" placeholder="Détails supplémentaires sur cette dépense..."></textarea>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-file-alt"></i> Pièce justificative :</label>
          <textarea name="piece_justificative" placeholder="Référence ou description de la pièce justificative..."></textarea>
        </div>
        
        <div class="btn-group">
          <button type="submit" class="btn btn-primary">
            <i class="fas fa-save"></i> Enregistrer
          </button>
          <a href="../index.php/dashboard" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Tableau de bord
          </a>
        </div>
      </form>
    </div>

    <div class="card">
      <h3 style="color: #dc3545; margin-bottom: 20px;"><i class="fas fa-list"></i> Liste des dépenses</h3>
      
      <div class="filter-controls">
        <div class="filter-group">
          <label for="searchInput"><i class="fas fa-search"></i> Rechercher :</label>
          <input type="text" id="searchInput" placeholder="Libellé, catégorie, statut..." 
                 title="Rechercher dans les dépenses">
        </div>
        
        <div class="filter-group">
          <label for="rowsPerPage"><i class="fas fa-table"></i> Lignes par page :</label>
          <select id="rowsPerPage" title="Nombre de lignes à afficher">
            <option value="5">5</option>
            <option value="10" selected>10</option>
            <option value="20">20</option>
            <option value="50">50</option>
            <option value="100">100</option>
          </select>
        </div>
      </div>
      
      <div class="table-responsive">
        <table id="depensesTable">
          <thead>
            <tr>
              <th><i class="fas fa-tag"></i> Libellé</th>
              <th><i class="fas fa-list"></i> Catégorie</th>
              <th><i class="fas fa-cog"></i> Type</th>
              <th><i class="fas fa-coins"></i> Montant</th>
              <th><i class="fas fa-info-circle"></i> Statut</th>
              <th><i class="fas fa-calendar-day"></i> Date</th>
              <th><i class="fas fa-cog"></i> Actions</th>
            </tr>
          </thead>
         <tbody>
            <?php foreach ($depenses as $d): 
              // Créer une classe CSS à partir du nom de la catégorie
              $categorieClass = 'categorie-' . $d['categories'];
            ?>
              <tr class="<?= $categorieClass ?>">
                <td><?= htmlspecialchars($d['libelles_depenses']) ?></td>
                <td><?= str_replace('_', ' ', $d['categories']) ?></td>
                <td>
                  <span class="badge <?= $d['type_depense'] === 'Fixe' ? 'badge-fixe' : 'badge-variable' ?>">
                    <?= $d['type_depense'] ?>
                  </span>
                </td>
                <td data-sort="<?= $d['montant_periodique'] ?>">
                  <?= number_format($d['montant_periodique'], 0, ',', ' ') ?> FCFA
                </td>
                <td>
                  <span class="badge <?= $d['statut_depense'] === 'Prévue' ? 'badge-prevue' : 'badge-realisee' ?>">
                    <?= $d['statut_depense'] ?>
                  </span>
                </td>
                <td data-sort="<?= strtotime($d['date_prevu_depense']) ?>">
                  <?= date('d/m/Y', strtotime($d['date_prevu_depense'])) ?>
                </td>
                <td class="actions">
                  <a href="../index.php/edit_depense/<?= $d['id_depense'] ?>" class="btn btn-primary btn-sm" title="Modifier">
                    <i class="fas fa-edit"></i>
                  </a>
                  <form method="POST" action="../index.php/delete_depense/<?= $d['id_depense'] ?>" onsubmit="return confirm('Supprimer cette dépense ?');" style="display:inline;">
                    <button type="submit" class="btn btn-danger btn-sm" title="Supprimer">
                      <i class="fas fa-trash-alt"></i>
                    </button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <footer>
    Discipline et liberté financière : la voie vers la richesse.
  </footer>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // Gestion des notifications
      const notification = document.getElementById('flashNotification');
      if (notification) {
        // Afficher la notification
        setTimeout(() => {
          notification.classList.add('show');
        }, 100);
        
        // Cacher la notification après 5 secondes
        setTimeout(() => {
          notification.classList.remove('show');
          notification.classList.add('hide');
        }, 5000);
      }
      
      // Filtrage et pagination améliorés
      const searchInput = document.getElementById('searchInput');
      const rowsPerPageSelect = document.getElementById('rowsPerPage');
      const tableBody = document.querySelector('table tbody');
      const allRows = Array.from(tableBody.querySelectorAll('tr'));
      let currentPage = 1;
      
      function filterAndPaginate() {
        const keyword = searchInput.value.toLowerCase();
        const rowsPerPage = parseInt(rowsPerPageSelect.value);
        let visibleCount = 0;
        
        allRows.forEach((row, index) => {
          const text = row.textContent.toLowerCase();
          const match = keyword === '' || text.includes(keyword);
          const isOnPage = index >= (currentPage - 1) * rowsPerPage && 
                          index < currentPage * rowsPerPage;
          
          if (match && isOnPage) {
            row.style.display = '';
            visibleCount++;
          } else {
            row.style.display = 'none';
          }
        });
        
        // Mettre à jour la pagination si nécessaire
        if (visibleCount === 0 && currentPage > 1) {
          currentPage--;
          filterAndPaginate();
        }
      }
      
      // Calcul automatique du montant annuel
      const periodiciteSelect = document.querySelector('select[name="periodicite"]');
      const montantPeriodique = document.querySelector('input[name="montant_periodique"]');
      const montantAnnuel = document.querySelector('input[name="montant_annuel_estimatif"]');
      
      function calculateAnnualAmount() {
        if (!periodiciteSelect.value || !montantPeriodique.value) return;
        
        const amount = parseFloat(montantPeriodique.value);
        if (isNaN(amount)) return;
        
        let multiplier;
        switch (periodiciteSelect.value) {
          case 'Journalière': multiplier = 365; break;
          case 'Hebdomadaire': multiplier = 52; break;
          case 'Mensuelle': multiplier = 12; break;
          case 'Trimestrielle': multiplier = 4; break;
          case 'Semestrielle': multiplier = 2; break;
          case 'Annuelle': multiplier = 1; break;
          default: multiplier = 1;
        }
        
        montantAnnuel.value = (amount * multiplier).toFixed(2);
      }
      
      periodiciteSelect.addEventListener('change', calculateAnnualAmount);
      montantPeriodique.addEventListener('input', calculateAnnualAmount);
      
      // Événements pour le filtrage
      searchInput.addEventListener('input', filterAndPaginate);
      rowsPerPageSelect.addEventListener('change', function() {
        currentPage = 1;
        filterAndPaginate();
      });
      
      // Initialisation
      filterAndPaginate();
      
      // Tri des colonnes
      const table = document.getElementById('depensesTable');
      const headers = table.querySelectorAll('th');
      
      headers.forEach((header, index) => {
        if (index < headers.length - 1) { // Exclure la colonne Actions
          header.style.cursor = 'pointer';
          header.addEventListener('click', () => {
            sortTable(index);
          });
        }
      });
      
      function sortTable(columnIndex) {
        const rows = Array.from(table.querySelectorAll('tbody tr'));
        const isAscending = !table.querySelector(`th:nth-child(${columnIndex + 1})`).classList.contains('asc');
        
        // Reset all headers
        headers.forEach(header => {
          header.classList.remove('asc', 'desc');
        });
        
        // Set current header
        const currentHeader = headers[columnIndex];
        currentHeader.classList.add(isAscending ? 'asc' : 'desc');
        
        rows.sort((a, b) => {
          const aValue = a.cells[columnIndex].getAttribute('data-sort') || a.cells[columnIndex].textContent;
          const bValue = b.cells[columnIndex].getAttribute('data-sort') || b.cells[columnIndex].textContent;
          
          // Try to compare as numbers
          const aNum = parseFloat(aValue);
          const bNum = parseFloat(bValue);
          
          if (!isNaN(aNum) && !isNaN(bNum)) {
            return isAscending ? aNum - bNum : bNum - aNum;
          }
          
          // Compare as strings
          return isAscending 
            ? aValue.localeCompare(bValue)
            : bValue.localeCompare(aValue);
        });
        
        // Rebuild table
        rows.forEach(row => table.querySelector('tbody').appendChild(row));
        filterAndPaginate();
      }
    });
    
    $(document).ready(function() {
        $('select[name="mode_paiement"]').select2({
            templateResult: formatOption,
            templateSelection: formatOption
        });
    });
    
    function formatOption(option) {
        if (!option.id) return option.text;
        return $('<span>' + option.text + '</span>');
    }

  </script>
</body>
</html>