<?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 revenus liés 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>
    /* Styles cohérents avec le dashboard */
    body {
      margin: 0;
      font-family: 'Segoe UI', sans-serif;
      background-color: #f4f6f8;
      color: #333;
    }

    h2 {
      background-color: #20c997; /* Couleur revenus_biens du dashboard */
      color: white;
      padding: 20px;
      margin: 0;
      text-align: center;
      font-size: 24px;
    }

    .container {
      max-width: 1200px;
      margin: 30px auto;
      padding: 0 20px;
    }

    .card {
      background-color: white;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
      padding: 25px;
      margin-bottom: 30px;
    }

    /* Alertes */
    .alert {
      padding: 15px;
      border-radius: 5px;
      margin-bottom: 20px;
    }

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

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

    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
    }

    input[type="text"],
    input[type="number"],
    input[type="date"],
    select,
    textarea {
      width: 100%;
      padding: 10px 15px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 15px;
      transition: border 0.3s;
    }

    input:focus,
    select:focus,
    textarea:focus {
      border-color: #20c997;
      outline: none;
      box-shadow: 0 0 0 3px rgba(32,201,151,0.1);
    }

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

    /* Boutons */
    .btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: 10px 20px;
      border-radius: 5px;
      text-decoration: none;
      font-weight: 500;
      transition: all 0.2s;
      border: none;
      cursor: pointer;
      font-size: 15px;
      margin : 5px;
    }

    .btn i {
      margin-right: 8px;
    }

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

    .btn-primary {
      background-color: #20c997;
      color: white;
    }

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

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

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

    .table-responsive {
      overflow-x: auto;
      margin-top: 20px;
    }
    
    /* Tableau */
    table {
      width: 100%;
      border-collapse: collapse;
      /*margin: 20px 0;*/
      background: white;
      border-radius: 10px;
      /*overflow: hidden;*/
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

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

    th {
      background-color: #20c997;
      color: white;
      font-weight: 500;
    }

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

    /* Filtres */
    .filters {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      margin-bottom: 20px;
      background: white;
      padding: 15px;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

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

    /* Actions */
    .actions {
      display: flex;
      gap: 5px;
    }

    .actions form {
      margin: 0;
    }

    /* Responsive */
    @media (max-width: 768px) {
      .container {
        padding: 0 15px;
      }
      
      th, td {
        padding: 8px 10px;
      }
      
      .filters {
        flex-direction: column;
        gap: 10px;
      }
      
      .actions {
        flex-direction: column;
      }
    }
    
.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-coins"></i> Gestion des revenus liés aux biens</h2>

  <div class="container">
    <!-- Section d'ajout -->
    <div class="card">
      <h3 style="margin-top: 0; color: #20c997;"><i class="fas fa-plus-circle"></i> Ajouter un revenu</h3>

      <?php if (!isset($biens)): ?>
        <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> La variable $biens n'est pas définie.</div>
      <?php elseif (empty($biens)): ?>
        <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Aucun bien trouvé pour cet utilisateur.</div>
      <?php endif; ?>

      <form method="POST" action="../index.php/store_revenus_biens">
        <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-tag"></i> Libellé du revenu :</label>
          <input type="text" name="libelle_revenu_bien" required>
        </div>

        <div class="form-group">
          <label><i class="fas fa-money-bill-wave"></i> Montant du revenu (FCFA) :</label>
          <input type="number" name="montant_revenu" step="0.01" required>
        </div>

        <div class="form-group">
          <label><i class="fas fa-list"></i> Type de revenu :</label>
          <input type="text" name="type_revenu_bien">
        </div>

        <div class="form-group">
          <label><i class="fas fa-search"></i> Origine du revenu :</label>
          <input type="text" name="origine_revenu">
        </div>

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

        <div class="form-group">
          <label><i class="fas fa-user-tie"></i> Responsable de la collecte :</label>
          <input type="text" name="responsable_collecte">
        </div>

        <div class="form-group">
          <label><i class="fas fa-file-alt"></i> Justificatif :</label>
          <textarea name="justificatif"></textarea>
        </div>

        <div class="form-group">
          <?php
            $moisActuel = date('n');
            $moisListe = [
              1 => 'Janvier', 2 => 'Fevrier', 3 => 'Mars', 4 => 'Avril',
              5 => 'Mai', 6 => 'Juin', 7 => 'Juillet', 8 => 'Aout',
              9 => 'Septembre', 10 => 'Octobre', 11 => 'Novembre', 12 => 'Decembre'
            ];
          ?>
          <label><i class="fas fa-calendar-alt"></i> Mois :</label>
          <select name="mois_revenu" 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>

        <div class="form-group">
          <?php $currentYear = date('Y'); ?>
          <label><i class="fas fa-calendar"></i> Année :</label>
          <select name="annee_revenu" 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>

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

    <!-- Section liste -->
    <div class="card">
      <h3 style="margin-top: 0; color: #20c997;"><i class="fas fa-list"></i> Liste des revenus enregistrés</h3>

      <div class="filters">
        <div class="filter-group">
          <label for="searchInput"><i class="fas fa-search"></i> Rechercher :</label>
          <input type="text" id="searchInput" placeholder="Libellé, bien, mois...">
        </div>

        <div class="filter-group">
          <label for="filterMonth"><i class="fas fa-calendar-alt"></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-tag"></i> Libellé</th>
            <th><i class="fas fa-money-bill-wave"></i> Montant</th>
            <th><i class="fas fa-calendar-alt"></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 ($revenus as $r): ?>
            <tr>
              <td><?= $r['id_revenus_biens'] ?></td>
              <td>
                <?php
                  $nomBien = '';
                  foreach ($biens as $b) {
                    if ($b['id_bien'] == $r['id_bien']) {
                      $nomBien = $b['libelle_bien'];
                      break;
                    }
                  }
                  echo htmlspecialchars($nomBien);
                ?>
              </td>
              <td><?= htmlspecialchars($r['libelle_revenu_bien']) ?></td>
              <td><?= number_format($r['montant_revenu'], 0, ',', ' ') ?> FCFA</td>
              <td><?= $r['mois_revenu'] ?></td>
              <td><?= $r['annee_revenu'] ?></td>
              <td class="actions">
                <form method="GET" action="../index.php/edit_revenus_biens/<?= $r['id_revenus_biens'] ?>">
                  <button type="submit" class="btn btn-primary btn-sm">
                    <i class="fas fa-edit"></i>
                  </button>
                </form>
                <form method="POST" action="../index.php/delete_revenus_biens/<?= $r['id_revenus_biens'] ?>" onsubmit="return confirm('Supprimer ce revenu ?');">
                  <button type="submit" class="btn btn-danger btn-sm">
                    <i class="fas fa-trash-alt"></i>
                  </button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
     </div>
    </div>
  </div>

  <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 libelle = cells[2]?.textContent.toLowerCase();
        const mois = cells[4]?.textContent;
        const annee = cells[5]?.textContent;

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

        row.style.display = (matchesSearch && matchesMonth && matchesYear) ? "" : "none";
      });
    }

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