<?php
if (session_status() === PHP_SESSION_NONE) @session_start();

// Gestion des messages flash
if (isset($_SESSION['flash'])) {
    $flashType = $_SESSION['flash']['type'];
    $flashMessage = $_SESSION['flash']['message'];
    unset($_SESSION['flash']);
    
    echo "<div class='alert alert-$flashType' role='alert'>
            <i class='fas " . 
            ($flashType === 'success' ? 'fa-check-circle' : 
             ($flashType === 'danger' ? 'fa-exclamation-circle' : 
              ($flashType === 'warning' ? 'fa-exclamation-triangle' : 'fa-info-circle'))) . 
            "'></i>
            $flashMessage
          </div>";
}

$id_utilisateur = $_SESSION['user']['id_utilisateur'];
$today = date('Y-m-d');
?>

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Gestion des biens -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 --> 
  <style>
    :root {
      --primary-color: #17a2b8;
      --secondary-color: #6c757d;
      --light-gray: #f8f9fa;
    }
    
    body {
      font-family: 'Segoe UI', system-ui, sans-serif;
      background-color: var(--light-gray);
      color: #212529;
      margin: 0;
    }
    
    h2 {
      background-color: var(--primary-color);
      color: white;
      padding: 1.25rem;
      margin: 0;
      font-size: 1.5rem;
      font-weight: 600;
      text-align: center;
    }
    
    .card-container {
      max-width: 1200px;
      margin: 2rem auto;
      padding: 0 1rem;
    }
    
    .card {
      background-color: white;
      border-radius: 0.5rem;
      box-shadow: 0 0.25rem 0.75rem rgba(0,0,0,0.05);
      margin-bottom: 2rem;
      padding: 1.5rem;
    }
    
    .card-title {
      color: var(--primary-color);
      margin-bottom: 1.25rem;
      font-size: 1.25rem;
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }
    
    .form-group {
      margin-bottom: 1.25rem;
    }
    
    .form-label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 500;
      color: #495057;
    }
    
    .form-control, .form-select {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid #ced4da;
      border-radius: 0.375rem;
      font-size: 1rem;
      transition: all 0.2s;
    }
    
    .form-control:focus, .form-select:focus {
      border-color: var(--primary-color);
      box-shadow: 0 0 0 0.25rem rgba(23, 162, 184, 0.25);
      outline: none;
    }
    
    .form-control::placeholder {
      color: #6c757d;
      opacity: 0.6;
    }
    
    textarea.form-control {
      min-height: 100px;
      resize: vertical;
    }
    
    .btn {
      font-weight: 500;
      padding: 0.75rem 1.5rem;
      border-radius: 0.375rem;
      transition: all 0.2s;
      display: inline-flex;
      align-items: center;
      gap: 0.5rem;
      border: none;
      cursor: pointer;
      text-decoration: none;
    }
    
    .btn-primary {
      background-color: var(--primary-color);
      color: white;
    }
    
    .btn-primary:hover {
      background-color: #138496;
    }
    
    .btn-secondary {
      background-color: var(--secondary-color);
      color: white;
    }
    
    .btn-secondary:hover {
      background-color: #5a6268;
    }
    
    .btn-group {
      display: flex;
      gap: 1rem;
      margin-top: 1.5rem;
    }
    
    .table-responsive {
      overflow-x: auto;
      margin-top: 1.25rem;
    }
    
    table {
      width: 100%;
      border-collapse: collapse;
    }
    
    th, td {
      padding: 1rem;
      text-align: left;
      border-bottom: 1px solid #dee2e6;
    }
    
    th {
      background-color: var(--primary-color);
      color: white;
      font-weight: 500;
    }
    
    tr:hover {
      background-color: rgba(0,0,0,0.02);
    }
    
    .badge {
      display: inline-block;
      padding: 0.35em 0.65em;
      font-size: 0.75em;
      font-weight: 500;
      line-height: 1;
      text-align: center;
      white-space: nowrap;
      vertical-align: baseline;
      border-radius: 50rem;
    }
    
    .badge-success {
      background-color: #d4edda;
      color: #155724;
    }
    
    .badge-warning {
      background-color: #fff3cd;
      color: #856404;
    }
    
    .badge-danger {
      background-color: #f8d7da;
      color: #721c24;
    }
    
    .actions {
      display: flex;
      gap: 0.5rem;
      flex-wrap: wrap;
    }
    
    .actions .btn {
      padding: 0.5rem;
      font-size: 0.875rem;
    }
    
    .filter-controls {
      display: flex;
      gap: 1rem;
      margin-bottom: 1.25rem;
      flex-wrap: wrap;
    }
    
    .filter-group {
      flex: 1;
      min-width: 200px;
    }
    
    .sum-info {
      font-size: 0.875rem;
      color: #28a745;
      margin-top: 0.25rem;
      font-weight: 500;
    }
    
    .sum-warning {
      color: #dc3545;
    }
    
    @media (max-width: 768px) {
      .btn-group {
        flex-direction: column;
      }
      
      .filter-controls {
        flex-direction: column;
        gap: 0.75rem;
      }
      
      .actions {
        flex-direction: column;
      }
    }
  </style>
</head>
<body>

  <h2><i class="fas fa-home"></i> Gestion des biens</h2>

  <div class="card-container">
    <!-- Formulaire d'ajout -->
    <div class="card">
      <h3 class="card-title"><i class="fas fa-plus-circle"></i> Ajouter un bien</h3>
      <form method="POST" action="../index.php/store_bien">
        <input type="hidden" name="id_utilisateur" value="<?= $id_utilisateur ?>">
        
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label class="form-label"><i class="fas fa-tag"></i> Libellé :</label>
              <input type="text" class="form-control" name="libelle_bien" required 
                     placeholder="Ex: Appartement centre-ville">
            </div>
            
            <div class="form-group">
              <label class="form-label"><i class="fas fa-list-alt"></i> Type de bien :</label>
              <select class="form-select" name="type_bien" required>
                <option value="">-- Sélectionnez --</option>
                <option value="Résidence principale">Résidence principale</option>
                <option value="Résidence secondaire">Résidence secondaire</option>
                <option value="Immeuble locatif">Immeuble locatif</option>
                <option value="Véhicule personnel">Véhicule personnel</option>
                <option value="Action cotée">Action cotée</option>
                <option value="Fonds d’investissement">Fonds d'investissement</option>
                <option value="Contrat d’assurance-vie">Contrat d'assurance-vie</option>
                <option value="Fonds de commerce">Fonds de commerce</option>
                <option value="Droit d’auteur">Droit d'auteur</option>
                <option value="Epoux/epouse">Epoux/epouse</option>
              </select>
            </div>
            
            <div class="form-group">
              <label class="form-label"><i class="fas fa-money-bill-wave"></i> Source de financement :</label>
              <select class="form-select" name="source_financement" required>
                <option value="">-- Sélectionnez --</option>
                <option value="Épargne">Épargne</option>
                <option value="Dette">Dette</option>
                <option value="Épargne et dette">Épargne et dette</option>
              </select>
            </div>
            
            <div class="form-group">
              <label class="form-label"><i class="fas fa-piggy-bank"></i> Épargne associée :</label>
              <select class="form-select" name="id_epargne_ct">
                <option value="">-- Aucune épargne --</option>
                <?php foreach ($epargnes as $e): ?>
                  <option value="<?= $e['id_epargne_ct'] ?>">
                    <?= htmlspecialchars($e['libelle_epargne']) ?> (<?= number_format($e['montant_actuel'], 0, ',', ' ') ?> FCFA)
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <div class="form-group">
              <label class="form-label"><i class="fas fa-file-invoice-dollar"></i> Dette associée :</label>
              <select class="form-select" name="id_dette">
                <option value="">-- Aucune dette --</option>
                <?php foreach ($dettes as $d): ?>
                  <option value="<?= $d['id_dette'] ?>">
                    <?= htmlspecialchars($d['libelle_dette']) ?> (<?= number_format($d['montant_emprunt'], 0, ',', ' ') ?> FCFA)
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="col-md-6">
            <div class="form-group">
              <label class="form-label"><i class="fas fa-coins"></i> Montant d'acquisition (FCFA) :</label>
              <input type="number" class="form-control" name="montant_acquisition" step="1000" min="0" required>
              <div id="sumInfo" class="sum-info"></div>
            </div>
            
            <div class="form-group">
              <label class="form-label"><i class="fas fa-calendar-day"></i> Date d'acquisition :</label>
              <input type="date" class="form-control" name="date_acquisition" max="<?= $today ?>" value="<?= $today ?>">
            </div>
            
            <div class="form-group">
              <label class="form-label"><i class="fas fa-chart-line"></i> Valeur actuelle (FCFA) :</label>
              <input type="number" class="form-control" name="valeur_actuelle" step="1000" min="0">
            </div>
            
            <div class="form-group">
              <label class="form-label"><i class="fas fa-percentage"></i> Taux de dépréciation (%) :</label>
              <input type="number" class="form-control" name="taux_depreciation" step="0.01" min="-100" max="100">
            </div>
          </div>
        </div>
        
        <div class="form-group">
          <label class="form-label"><i class="fas fa-align-left"></i> Description :</label>
          <textarea class="form-control" name="description" placeholder="Détails sur le bien..."></textarea>
        </div>
        
        <div class="row">
          <div class="col-md-4">
            <div class="form-group">
              <label class="form-label"><i class="fas fa-user-tie"></i> Responsable de gestion :</label>
              <input type="text" class="form-control" name="responsable_gestion" placeholder="Nom du responsable">
            </div>
          </div>
          
          <div class="col-md-4">
            <div class="form-group">
              <label class="form-label"><i class="fas fa-calendar-alt"></i> Fréquence d'utilisation :</label>
              <select class="form-select" name="frequence_utilisation">
                <option value="Mensuelle" selected>Mensuelle</option>
                <option value="Journalière">Journalière</option>
                <option value="Hebdomadaire">Hebdomadaire</option>
                <option value="Trimestrielle">Trimestrielle</option>
                <option value="Semestrielle">Semestrielle</option>
                <option value="Annuelle">Annuelle</option>
              </select>
            </div>
          </div>
          
          <div class="col-md-4">
            <div class="form-group">
              <label class="form-label"><i class="fas fa-tags"></i> Catégorie :</label>
              <select class="form-select" name="categorie_bien" required>
                <option value="">-- Sélectionnez --</option>
                <option value="immobilier">Immobilier</option>
                <option value="mobilier">Mobilier</option>
                <option value="financier">Financier</option>
                <option value="professionnel">Professionnel</option>
                <option value="incorporel">Incorporel</option>
              </select>
            </div>
          </div>
        </div>
        
        <div class="form-group">
          <label class="form-label"><i class="fas fa-info-circle"></i> Statut :</label>
          <select class="form-select" name="statut" required>
            <option value="actif" selected>Actif</option>
            <option value="passif">Passif</option>
            <option value="vendu">Vendu</option>
            <option value="non actif">Non actif</option>
          </select>
        </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> Retour
          </a>
        </div>
      </form>
    </div>

    <!-- Liste des biens -->
    <div class="card">
      <h3 class="card-title"><i class="fas fa-list"></i> Liste des biens</h3>
      
      <div class="filter-controls">
        <div class="filter-group">
          <label class="form-label"><i class="fas fa-search"></i> Rechercher :</label>
          <input type="text" id="searchInput" class="form-control" placeholder="Libellé, type, statut...">
        </div>
        
        <div class="filter-group">
          <label class="form-label"><i class="fas fa-table"></i> Lignes par page :</label>
          <select id="rowsPerPage" class="form-select">
            <option value="5">5</option>
            <option value="10" selected>10</option>
            <option value="20">20</option>
            <option value="50">50</option>
          </select>
        </div>
      </div>
      
      <div class="table-responsive">
        <table>
          <thead>
            <tr>
              <th><i class="fas fa-tag"></i> Libellé</th>
              <th><i class="fas fa-list-alt"></i> Type</th>
              <th><i class="fas fa-coins"></i> Valeur</th>
              <th><i class="fas fa-info-circle"></i> Statut</th>
              <th><i class="fas fa-cog"></i> Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($biens as $b): ?>
              <tr>
                <td><?= htmlspecialchars($b['libelle_bien']) ?></td>
                <td><?= htmlspecialchars($b['type_bien']) ?></td>
                <td><?= number_format($b['valeur_actuelle'], 0, ',', ' ') ?> FCFA</td>
                <td>
                  <?php
                    $badgeClass = 'badge-warning';
                    if ($b['statut'] === 'actif') $badgeClass = 'badge-success';
                    elseif ($b['statut'] === 'passif') $badgeClass = 'badge-danger';
                  ?>
                  <span class="badge <?= $badgeClass ?>"><?= ucfirst($b['statut']) ?></span>
                </td>
                <td class="actions">
                  <a href="../index.php/edit_bien/<?= $b['id_bien'] ?>" class="btn btn-primary" title="Modifier">
                    <i class="fas fa-edit"></i>
                  </a>
                  <form method="POST" action="../index.php/delete_bien/<?= $b['id_bien'] ?>" 
                        onsubmit="return confirm('Supprimer ce bien ?');" style="display:inline;">
                    <button type="submit" class="btn btn-danger" title="Supprimer">
                      <i class="fas fa-trash-alt"></i>
                    </button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <script>
    // Calcul de la somme disponible
    document.addEventListener('DOMContentLoaded', function() {
      const epargneSelect = document.querySelector('select[name="id_epargne_ct"]');
      const detteSelect = document.querySelector('select[name="id_dette"]');
      const montantInput = document.querySelector('input[name="montant_acquisition"]');
      const sumInfo = document.getElementById('sumInfo');
      
      const epargnes = {
        <?php foreach ($epargnes as $e): ?>
          '<?= $e['id_epargne_ct'] ?>': <?= $e['montant_actuel'] ?>,
        <?php endforeach; ?>
      };
      
      const dettes = {
        <?php foreach ($dettes as $d): ?>
          '<?= $d['id_dette'] ?>': <?= $d['montant_emprunt'] ?>,
        <?php endforeach; ?>
      };
      
      function updateSumInfo() {
        let total = 0;
        
        if (epargneSelect.value && epargnes[epargneSelect.value]) {
          total += parseFloat(epargnes[epargneSelect.value]);
        }
        
        if (detteSelect.value && dettes[detteSelect.value]) {
          total += parseFloat(dettes[detteSelect.value]);
        }
        
        if (total > 0) {
          sumInfo.textContent = `Total disponible: ${total.toLocaleString('fr-FR')} FCFA`;
          sumInfo.className = 'sum-info';
          
          // Validation du montant
          if (montantInput.value && parseFloat(montantInput.value) > total) {
            sumInfo.textContent += ' - Montant trop élevé';
            sumInfo.className = 'sum-info sum-warning';
          }
        } else {
          sumInfo.textContent = '';
        }
      }
      
      epargneSelect.addEventListener('change', updateSumInfo);
      detteSelect.addEventListener('change', updateSumInfo);
      montantInput.addEventListener('input', updateSumInfo);
      
      // Filtrage et pagination
      const searchInput = document.getElementById('searchInput');
      const rowsPerPageSelect = document.getElementById('rowsPerPage');
      const tableRows = Array.from(document.querySelectorAll('tbody tr'));
      
      function filterTable() {
        const searchTerm = searchInput.value.toLowerCase();
        const rowsToShow = parseInt(rowsPerPageSelect.value);
        let visibleCount = 0;
        
        tableRows.forEach(row => {
          const text = row.textContent.toLowerCase();
          const match = searchTerm === '' || text.includes(searchTerm);
          
          if (match && visibleCount < rowsToShow) {
            row.style.display = '';
            visibleCount++;
          } else {
            row.style.display = 'none';
          }
        });
      }
      
      searchInput.addEventListener('input', filterTable);
      rowsPerPageSelect.addEventListener('change', filterTable);
      filterTable();
    });
  </script>
</body>
</html>