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

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 liées aux biens - Gespes360</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 --> 
  
  
  <style>
    body {
      margin: 0;
      font-family: 'Segoe UI', sans-serif;
      background-color: #f4f6f8;
      color: #333;
    }

    h2 {
      background-color: #fd7e14; /* Couleur dépenses biens du dashboard */
      color: white;
      padding: 20px;
      margin: 0;
      text-align: center;
      font-size: 24px;
    }

    .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: 1000px;
    }

    .alert {
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
      background-color: #fff3cd;
      color: #856404;
      border: 1px solid #ffeeba;
    }

    .alert-danger {
      background-color: #f8d7da;
      color: #721c24;
      border-color: #f5c6cb;
    }

    .form-group {
      margin-bottom: 20px;
    }

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

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

    .form-group input:focus,
    .form-group select:focus,
    .form-group textarea:focus {
      border-color: #fd7e14;
      outline: none;
      box-shadow: 0 0 0 3px rgba(253, 126, 20, 0.2);
    }

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

    .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: #fd7e14; /* Couleur dépenses biens */
    }

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

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

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

    .btn-success {
      background-color: #17a2b8;
    }

    .btn-success:hover {
      background-color: #218838;
    }

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

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

    .btn-info {
      background-color: #17a2b8;
    }

    .btn-info:hover {
      background-color: #138496;
    }

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

    .table-responsive {
      overflow-x: auto;
      margin-top: 20px;
    }

    .table-responsive {
      overflow-x: auto;
      margin-top: 20px;
    }
    
    table {
      width: 100%;
      border-collapse: collapse;
      margin: 20px 0;
    }

    th, td {
      padding: 12px 15px;
      text-align: left;
      border-bottom: 1px solid #ddd;
    }

    th {
      background-color: #fd7e14; /* Couleur dépenses biens */
      color: white;
      font-weight: 600;
    }

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

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

    .actions form {
      margin: 0;
    }

    .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;
      border: 1px solid #ddd;
      border-radius: 8px;
    }

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

    @media (max-width: 768px) {
      .card {
        padding: 15px;
      }
      
      .actions {
        flex-direction: column;
      }
      
      .btn {
        width: 100%;
      }
      
      .filter-controls {
        flex-direction: column;
        gap: 10px;
      }
    }
    
.alert {
    display: flex;
    align-items: center;
    gap: 10px;
    border: 1px solid transparent;
}
.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;
}

  </style>
</head>
 
<body>
  <h2><i class="fas fa-chart-line"></i> Dépenses liées aux biens</h2>

  <div class="card-container">
    <div class="card">
      <h3 style="color: #fd7e14; margin-bottom: 20px;"><i class="fas fa-plus-circle"></i> Ajouter une dépense</h3>
      
      <?php if (!isset($biens)): ?>
        <div class="alert alert-danger"><i class="fas fa-exclamation-triangle"></i> La variable $biens n'est pas définie.</div>
      <?php elseif (empty($biens)): ?>
        <div class="alert"><i class="fas fa-info-circle"></i> Aucun bien trouvé pour cet utilisateur.</div>
      <?php endif; ?>

      <form method="POST" action="../index.php/store_depense_bien">
        <div class="form-group">
          <label><i class="fas fa-home"></i> Bien concerné :</label>
          <select name="id_bien" required>
            <option value="">-- Sélectionner un bien --</option>
            <?php 
                $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
                $uri = str_replace('/www.patrimoine360.com/public/index.php/', '', $uri);
                $segments = explode('/', trim($uri, '/'));
                $route = $segments[0] ?? null;
                $id_bien = $segments[1] ?? null;
            ?>
            <?php foreach ($biens as $b): ?>
              <option value="<?= $b['id_bien'] ?>" <?= ($b['id_bien'] == $id_bien) ? 'selected' : '' ?>>
                <?= htmlspecialchars($b['libelle_bien']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-coins"></i> Montant de la dépense :</label>
          <input type="number" name="montant_depense" step="0.01" required>
        </div>

        <div class="form-group">
          <label><i class="fas fa-comment-alt"></i> Motif spécifique :</label>
          <textarea name="motif_depense_bien"></textarea>
        </div>

        <div class="form-group">
          <label><i class="fas fa-calendar-alt"></i> Fréquence :</label>
          <select name="frequence_depense">
            <option>Mensuelle</option>
            <option>Trimestrielle</option>
            <option>Annuelle</option>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-comment"></i> Motif général :</label>
          <input type="text" name="motif_depense">
        </div>

        <div class="form-group">
          <label><i class="fas fa-file-alt"></i> Pièce justificative :</label>
          <input type="text" name="piece_justificative">
        </div>

        <?php
          $moisActuel = date('n');
          $moisListe = [
            1 => 'Janvier', 2 => 'Février', 3 => 'Mars', 4 => 'Avril',
            5 => 'Mai', 6 => 'Juin', 7 => 'Juillet', 8 => 'Août',
            9 => 'Septembre', 10 => 'Octobre', 11 => 'Novembre', 12 => 'Décembre'
          ];
        ?>
        <div class="form-group">
          <label><i class="fas fa-calendar-day"></i> Mois :</label>
          <select name="mois_depense" required>
            <option value="">-- Sélectionner le mois --</option>
            <?php foreach ($moisListe as $num => $nom): ?>
              <option value="<?= $nom ?>" <?= ($num == $moisActuel) ? 'selected' : '' ?>>
                <?= $nom ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <?php $currentYear = date('Y'); ?>
        <div class="form-group">
          <label><i class="fas fa-calendar"></i> Année :</label>
          <select name="annee_depense" required>
            <option value="">-- Sélectionner l'année --</option>
            <?php for ($year = 2025; $year <= 2055; $year++): ?>
              <option value="<?= $year ?>" <?= ($year == $currentYear) ? 'selected' : '' ?>>
                <?= $year ?>
              </option>
            <?php endfor; ?>
          </select>
        </div>

        <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>
        <a href="../index.php/biens" class="btn btn-success"><i class="fas fa-home"></i> Gestion des biens</a>
      </form>
    </div>

    <div class="card">
      <h3 style="color: #fd7e14; 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> Recherche :</label>
          <input type="text" id="searchInput" placeholder="Rechercher dans le tableau...">
        </div>

        <div class="filter-group">
          <label for="filterMonth"><i class="fas fa-calendar-day"></i> Mois :</label>
          <select id="filterMonth">
            <option value="">-- Tous les mois --</option>
            <?php foreach ($moisListe as $nom): ?>
              <option value="<?= $nom ?>"><?= $nom ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="filter-group">
          <label for="filterYear"><i class="fas fa-calendar"></i> Année :</label>
          <select id="filterYear">
            <option value="">-- Toutes les années --</option>
            <?php for ($year = 2025; $year <= 2055; $year++): ?>
              <option value="<?= $year ?>"><?= $year ?></option>
            <?php endfor; ?>
          </select>
        </div>
      </div>

      <div class="table-responsive">
        <table>
          <thead>
            <tr>
              <th><i class="fas fa-hashtag"></i> ID</th>
              <th><i class="fas fa-home"></i> Bien</th>
              <th><i class="fas fa-coins"></i> Montant</th>
              <th><i class="fas fa-comment-alt"></i> Motif</th>
              <th><i class="fas fa-calendar-day"></i> Mois</th>
              <th><i class="fas fa-calendar"></i> Année</th>
              <th><i class="fas fa-cog"></i> Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($depenses as $d): ?>
              <tr>
                <td><?= $d['id_depenses_biens'] ?></td>
                <td>
                  <?php
                    $nomBien = '';
                    foreach ($biens as $b) {
                      if ($b['id_bien'] == $d['id_bien']) {
                        $nomBien = $b['libelle_bien'];
                        break;
                      }
                    }
                    echo htmlspecialchars($nomBien);
                  ?>
                </td>
                <td><?= number_format($d['montant_depense'], 0, ',', ' ') ?> FCFA</td>
                <td><?= htmlspecialchars($d['motif_depense_bien']) ?></td>
                <td><?= $d['mois_depense'] ?></td>
                <td><?= $d['annee_depense'] ?></td>
                <td class="actions">
                  <form method="GET" action="../index.php/edit_depense_bien/<?= $d['id_depenses_biens'] ?>">
                    <button type="submit" class="btn btn-info btn-sm"><i class="fas fa-edit"></i> Modifier</button>
                  </form>
                  <form method="POST" action="../index.php/delete_depense_bien/<?= $d['id_depenses_biens'] ?>" onsubmit="return confirm('Supprimer cette dépense ?');">
                    <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i> Supprimer</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

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

  <script>
    const searchInput = document.getElementById("searchInput");
    const filterMonth = document.getElementById("filterMonth");
    const filterYear = document.getElementById("filterYear");
    const tableRows = document.querySelectorAll("table tbody tr");

    function filterTable() {
      const searchText = searchInput.value.toLowerCase();
      const selectedMonth = filterMonth.value;
      const selectedYear = filterYear.value;

      tableRows.forEach(row => {
        const cells = row.querySelectorAll("td");
        const bien = cells[1]?.textContent.toLowerCase();
        const motif = cells[3]?.textContent.toLowerCase();
        const mois = cells[4]?.textContent;
        const annee = cells[5]?.textContent;

        const matchesSearch = bien.includes(searchText) || motif.includes(searchText);
        const matchesMonth = !selectedMonth || mois === selectedMonth;
        const matchesYear = !selectedYear || annee === selectedYear;

        if (matchesSearch && matchesMonth && matchesYear) {
          row.style.display = "";
        } else {
          row.style.display = "none";
        }
      });
    }

    searchInput.addEventListener("input", filterTable);
    filterMonth.addEventListener("change", filterTable);
    filterYear.addEventListener("change", filterTable);
  </script>
</body>
</html>