<?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-edit"></i> Modifier un bien</h2>

  <div class="card-container">
    <div class="card">
      <h3 class="card-title"><i class="fas fa-home"></i> Modification du bien</h3>
      <form method="POST" action="../update_bien/<?= $bien['id_bien'] ?>">
        <input type="hidden" name="id_utilisateur" value="<?= $id_utilisateur ?>">
        
        <div class="form-row">
          <div class="form-col">
            <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 
                     value="<?= htmlspecialchars($bien['libelle_bien']) ?>">
            </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>
                <?php
                  $types = [
                    'Résidence principale', 'Résidence secondaire', 'Immeuble locatif',
                    'Véhicule personnel', 'Action cotée', 'Fonds d\'investissement',
                    'Contrat d\'assurance-vie', 'Fonds de commerce', 'Droit d\'auteur',
                    'Epoux/epouse'
                  ];
                  foreach ($types as $type) {
                    $selected = ($bien['type_bien'] === $type) ? 'selected' : '';
                    echo "<option value=\"$type\" $selected>$type</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>
                <?php
                  $sources = ['Épargne', 'Dette', 'Épargne et dette'];
                  foreach ($sources as $src) {
                    $selected = ($bien['source_financement'] === $src) ? 'selected' : '';
                    echo "<option value=\"$src\" $selected>$src</option>";
                  }
                ?>
              </select>
            </div>
          </div>
          
          <div class="form-col">
            <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
                     value="<?= $bien['montant_acquisition'] ?>">
              <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="<?= $bien['date_acquisition'] ?>">
            </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"
                     value="<?= $bien['valeur_actuelle'] ?>">
            </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"><?= htmlspecialchars($bien['description']) ?></textarea>
        </div>
        
        <div class="form-row">
          <div class="form-col">
            <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'] ?>" <?= $bien['id_epargne_ct'] == $e['id_epargne_ct'] ? 'selected' : '' ?>>
                    <?= 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'] ?>" <?= $bien['id_dette'] == $d['id_dette'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($d['libelle_dette']) ?> (<?= number_format($d['montant_emprunt'], 0, ',', ' ') ?> FCFA)
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="form-col">
            <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" 
                     value="<?= htmlspecialchars($bien['responsable_gestion']) ?>">
            </div>
            
            <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">
                <?php
                  $frequences = ['Journalière', 'Hebdomadaire', 'Mensuelle', 'Trimestrielle', 'Semestrielle', 'Annuelle'];
                  foreach ($frequences as $f) {
                    $selected = ($bien['frequence_utilisation'] === $f) ? 'selected' : '';
                    echo "<option value=\"$f\" $selected>$f</option>";
                  }
                ?>
              </select>
            </div>
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-col">
            <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"
                     value="<?= $bien['taux_depreciation'] ?>">
            </div>
          </div>
          
          <div class="form-col">
            <div class="form-group">
              <label class="form-label"><i class="fas fa-coins"></i> Bénéfice produit (FCFA) :</label>
              <input type="number" class="form-control" name="benefice_produit" step="1000"
                     value="<?= $bien['benefice_produit'] ?>">
            </div>
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-col">
            <div class="form-group">
              <label class="form-label"><i class="fas fa-info-circle"></i> Statut :</label>
              <select class="form-select" name="statut" required>
                <?php
                  $statuts = ['actif', 'passif', 'vendu', 'non actif'];
                  foreach ($statuts as $s) {
                    $selected = ($bien['statut'] === $s) ? 'selected' : '';
                    echo "<option value=\"$s\" $selected>" . ucfirst($s) . "</option>";
                  }
                ?>
              </select>
            </div>
          </div>
          
          <div class="form-col">
            <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>
                <?php
                  $categories = ['immobilier', 'mobilier', 'financier', 'professionnel', 'incorporel'];
                  foreach ($categories as $cat) {
                    $selected = ($bien['categorie_bien'] === $cat) ? 'selected' : '';
                    echo "<option value=\"$cat\" $selected>" . ucfirst($cat) . "</option>";
                  }
                ?>
              </select>
            </div>
          </div>
        </div>
        
        <div class="form-group">
          <label class="form-label"><i class="fas fa-history"></i> Historique des valeurs :</label>
          <textarea class="form-control" name="historique_valeurs"><?= htmlspecialchars($bien['historique_valeurs']) ?></textarea>
        </div>
        
        <div class="btn-group">
          <button type="submit" class="btn btn-primary">
            <i class="fas fa-save"></i> Enregistrer
          </button>
          <a href="../biens" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Annuler
          </a>
        </div>
      </form>
    </div>
  </div>

  <script>
    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';
          
          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);
      
      updateSumInfo();
    });
  </script>
</body>
</html>