<?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 dettes - 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: #ffc107; /* Couleur dettes du dashboard */
      color: #212529;
      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: 1200px;
    }

    .notification {
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 15px 20px;
      border-radius: 5px;
      color: white;
      z-index: 1000;
      animation: slideIn 0.5s forwards, fadeOut 0.5s 4.5s forwards;
      display: flex;
      align-items: center;
      gap: 10px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }

    .notification-success {
      background-color: #28a745;
    }

    .notification-error {
      background-color: #e74c3c;
    }

    @keyframes slideIn {
      from { transform: translateX(100%); opacity: 0; }
      to { transform: translateX(0); opacity: 1; }
    }

    @keyframes fadeOut {
      to { opacity: 0; }
    }

    .notification:hover {
      animation: slideIn 0.5s forwards;
    }

    .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: #ffc107;
      outline: none;
      box-shadow: 0 0 0 3px rgba(255, 193, 7, 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: #ffc107;
      color: #212529;
    }

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

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

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

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

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

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

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

    .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: #ffc107;
      color: #212529;
      font-weight: 600;
    }

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

    .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-success {
      background-color: #d4edda;
      color: #155724;
    }

    .badge-warning {
      background-color: #fff3cd;
      color: #856404;
    }

    .badge-danger {
      background-color: #f8d7da;
      color: #721c24;
    }

    .priority-high {
      color: #dc3545;
      font-weight: bold;
    }

    .priority-medium {
      color: #ffc107;
    }

    .priority-low {
      color: #28a745;
    }

    .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;
    }

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

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

    @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;
      }
    }
    
.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-file-invoice-dollar"></i> Gestion des dettes</h2>

  <div class="card-container">
    <div class="card">
      <h3 style="color: #ffc107; margin-bottom: 20px;"><i class="fas fa-plus-circle"></i> Ajouter une dette</h3>
      <form method="POST" action="../index.php/store_dette">
        <input type="hidden" name="id_contracteur" value="<?= $id_utilisateur ?>">
        
        <div class="form-group">
          <label><i class="fas fa-tag"></i> Libellé :</label>
          <input type="text" name="libelle_dette" required placeholder="Ex: Prêt bancaire">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-coins"></i> Montant emprunté (FCFA) :</label>
          <input type="number" name="montant_emprunt" step="0.01" required>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-money-bill-wave"></i> Montant remboursement (FCFA) :</label>
          <input type="number" name="montant_remboursement" step="0.01">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-percentage"></i> Taux d'intérêt (%) :</label>
          <input type="number" name="taux_d_interest" step="0.01">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-wallet"></i> Compte associé :</label>
          <select name="id_compte" required>
            <?php foreach ($comptes as $c): ?>
              <option value="<?= $c['id_compte'] ?>"><?= htmlspecialchars($c['nom_compte']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-user-tie"></i> Octroyeur :</label>
          <select name="id_octroyeur">
            <option value="">-- Aucun --</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-list"></i> Type de dette :</label>
          <input type="text" name="type_dette" placeholder="Ex: Prêt personnel">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-search"></i> Origine de la dette :</label>
          <textarea name="origine_dette" placeholder="Détails sur l'origine de la dette"></textarea>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-shield-alt"></i> Garantie :</label>
          <textarea name="garantie" placeholder="Garanties associées à cette dette"></textarea>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-info-circle"></i> Statut :</label>
          <select name="statut" required>
            <option value="active">Active</option>
            <option value="remboursée">Remboursée</option>
            <option value="annulée">Annulée</option>
          </select>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-exclamation-circle"></i> Priorité :</label>
          <select name="niveau_priorite" required>
            <option value="haute">Haute</option>
            <option value="moyenne" selected>Moyenne</option>
            <option value="basse">Basse</option>
          </select>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-calendar-day"></i> Date emprunt :</label>
          <input type="date" name="date_emprunt" required>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-calendar-check"></i> Date remboursement :</label>
          <input type="date" name="date_remboursement">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-history"></i> Historique des remboursements :</label>
          <textarea name="historique_remboursements" placeholder="Détails des remboursements effectués"></textarea>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-align-left"></i> Description :</label>
          <textarea name="description" placeholder="Informations complémentaires"></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: #ffc107; margin-bottom: 20px;"><i class="fas fa-list"></i> Liste des dettes</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é, statut, priorité...">
        </div>
        
        <div class="filter-group">
          <label for="rowsPerPage"><i class="fas fa-table"></i> Lignes par page :</label>
          <select id="rowsPerPage">
            <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>
          <thead>
            <tr>
              <th><i class="fas fa-tag"></i> Libellé</th>
              <th><i class="fas fa-coins"></i> Montant</th>
              <th><i class="fas fa-money-bill-wave"></i> Remboursement</th>
              <th><i class="fas fa-info-circle"></i> Statut</th>
              <th><i class="fas fa-exclamation-circle"></i> Priorité</th>
              <th><i class="fas fa-cog"></i> Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($dettes)): ?>
              <tr>
                <td colspan="6" class="no-results">
                  <i class="fas fa-info-circle"></i> Aucune dette enregistrée
                </td>
              </tr>
            <?php else: ?>
              <?php foreach ($dettes as $d): ?>
                <tr>
                  <td><?= htmlspecialchars($d['libelle_dette']) ?></td>
                  <td><?= number_format($d['montant_emprunt'], 0, ',', ' ') ?> FCFA</td>
                  <td><?= number_format($d['montant_remboursement'], 0, ',', ' ') ?> FCFA</td>
                  <td>
                    <?php
                      $badgeClass = 'badge-warning';
                      if ($d['statut'] === 'remboursée') $badgeClass = 'badge-success';
                      if ($d['statut'] === 'annulée') $badgeClass = 'badge-danger';
                    ?>
                    <span class="badge <?= $badgeClass ?>">
                      <?= ucfirst($d['statut']) ?>
                    </span>
                  </td>
                  <td class="priority-<?= $d['niveau_priorite'] ?>">
                    <?= ucfirst($d['niveau_priorite']) ?>
                  </td>
                  <td class="actions">
                    <a href="../index.php/edit_dette/<?= $d['id_dette'] ?>" class="btn btn-primary btn-sm" title="Modifier">
                      <i class="fas fa-edit"></i>
                    </a>
                    <form method="POST" action="../index.php/delete_dette/<?= $d['id_dette'] ?>" onsubmit="return confirm('Supprimer cette dette ?');" 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; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

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

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      const searchInput = document.getElementById('searchInput');
      const rowsPerPageSelect = document.getElementById('rowsPerPage');
      const tableBody = document.querySelector('table tbody');
      const allRows = Array.from(tableBody.querySelectorAll('tr:not(.no-results)'));
      
      function filterAndPaginate() {
        const keyword = searchInput.value.toLowerCase();
        const rowsPerPage = parseInt(rowsPerPageSelect.value);
        let visibleCount = 0;
        
        allRows.forEach(row => {
          const text = row.textContent.toLowerCase();
          const match = keyword === '' || text.includes(keyword);
          
          if (match && visibleCount < rowsPerPage) {
            row.style.display = '';
            visibleCount++;
          } else {
            row.style.display = 'none';
          }
        });
        
        const noResultsRow = tableBody.querySelector('.no-results');
        if (noResultsRow) {
          noResultsRow.style.display = visibleCount === 0 && keyword === '' ? '' : 'none';
        }
      }
      
      searchInput.addEventListener('input', filterAndPaginate);
      rowsPerPageSelect.addEventListener('change', filterAndPaginate);
      filterAndPaginate();
    });
  </script>
</body>
</html>