<?php
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'];
$today = date('Y-m-d');
?>

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Gestion des épargnes CT - BeWise</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <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" />
  <!-- CSS INCLUDE -->        
  
  <style>
    body {
      margin: 0;
      font-family: 'Segoe UI', sans-serif;
      background-color: #f4f6f8;
      color: #333;
    }

    h2 {
      background-color: #28a745;
      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: 1200px;
    }

    .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: #28a745;
      outline: none;
      box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.2);
    }

    .form-group input::placeholder,
    .form-group textarea::placeholder {
      color: #999;
      opacity: 0.7;
    }

    .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: #28a745;
    }

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

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

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

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

    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: #28a745;
      color: white;
      font-weight: 600;
    }

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

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

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

    .progress-container {
      width: 100%;
      background-color: #e9ecef;
      border-radius: 8px;
      height: 8px;
      margin-top: 5px;
    }

    .progress-bar {
      height: 100%;
      border-radius: 8px;
      background-color: #28a745;
      transition: width 0.5s ease;
    }

    .filter-controls {
      display: flex;
      gap: 20px;
      margin-bottom: 20px;
    }

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

    /* Améliorations spécifiques */
    .form-group input[type="date"] {
      padding: 11px 12px;
    }

    .form-group input[type="number"] {
      padding: 12px 15px;
    }

    .card-title {
      color: #28a745;
      margin-bottom: 20px;
      font-size: 20px;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .table-responsive {
      overflow-x: auto;
    }

    @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;
      }
    }
  </style>
</head>
<body>

  <h2><i class="fas fa-piggy-bank"></i> Gestion des épargnes CT</h2>

  <div class="card-container">
    <div class="card">
      <h3 class="card-title"><i class="fas fa-plus-circle"></i> Ajouter une épargne</h3>
      <form method="POST" action="../index.php/store_epargne_ct">
        <input type="hidden" name="id_utilisateur" value="<?= $id_utilisateur ?>">
        
        <div class="form-group">
          <label><i class="fas fa-tag"></i> Libellé :</label>
          <input type="text" name="libelle_epargne" required 
                 placeholder="Ex: Épargne vacances 2024"
                 title="Nommez votre objectif d'épargne">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-bullseye"></i> Objectif :</label>
          <input type="text" name="objectif" required 
                 placeholder="Ex: Voyage en famille à Bali"
                 title="Décrivez l'objectif de cette épargne">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-list"></i> Type d'épargne :</label>
          <select name="type_epargne" required title="Sélectionnez le type d'épargne">
            <option value="" disabled selected>-- Choisir un type --</option>
            <?php
              $types = ['Épargne structurelle','Constitution capitale','Fonds d\'urgence',
                       'Stabilisation budgetaire','Épargne projetée','Objectif achat',
                       'Objectif etudes','Objectif evenement','Épargne stratégique',
                       'Investissement financier','Plan retraite','Optimisation fiscale'];
              foreach ($types as $type) {
                echo "<option value=\"$type\">$type</option>";
              }
            ?>
          </select>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-wallet"></i> Compte associé :</label>
          <select name="id_compte" required title="Sélectionnez le compte à utiliser">
            <option value="" disabled selected>-- Choisir un compte --</option>
            <?php foreach ($comptes as $c): ?>
              <option value="<?= $c['id_compte'] ?>">
                <?= htmlspecialchars($c['nom_compte']) ?> (<?= $c['type_compte'] ?> - <?= $c['devise'] ?>)
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-exclamation-circle"></i> Priorité :</label>
          <select name="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-info-circle"></i> Statut :</label>
          <select name="statut" required>
            <option value="en_cours" selected>En cours</option>
            <option value="atteint">Atteint</option>
            <option value="reporté">Reporté</option>
          </select>
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-coins"></i> Montant visé (FCFA) :</label>
          <input type="number" name="montant_vise" step="1000" min="1" required
                 placeholder="500000" title="Montant total à atteindre">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-money-bill-wave"></i> Montant actuel (FCFA) :</label>
          <input type="number" name="montant_actuel" step="1000" min="0" required
                 placeholder="0" title="Montant déjà épargné">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-calendar-day"></i> Date d'échéance :</label>
          <input type="date" name="date_echeance" required
                 min="<?= $today ?>" value="<?= date('Y-m-d', strtotime('+1 month')) ?>"
                 title="Date butoir pour atteindre l'objectif">
        </div>
        
        <div class="form-group">
          <label><i class="fas fa-comment"></i> Commentaire :</label>
          <textarea name="commentaire" placeholder="Notes, détails ou rappels..."></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 class="card-title"><i class="fas fa-list"></i> Liste des épargnes</h3>
      
      <div class="filter-controls">
        <div class="filter-group">
          <label><i class="fas fa-search"></i> Rechercher :</label>
          <input type="text" id="searchInput" placeholder="Libellé, objectif, type...">
        </div>
        
        <div class="filter-group">
          <label><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>
          </select>
        </div>
      </div>
      
      <div class="table-responsive">
        <table>
          <thead>
            <tr>
              <th><i class="fas fa-tag"></i> Libellé</th>
              <th><i class="fas fa-bullseye"></i> Objectif</th>
              <th><i class="fas fa-wallet"></i> Compte</th>
              <th><i class="fas fa-coins"></i> Montant visé</th>
              <th><i class="fas fa-money-bill-wave"></i> Montant actuel</th>
              <th><i class="fas fa-chart-line"></i> Progression</th>
              <th><i class="fas fa-info-circle"></i> Statut</th>
              <th><i class="fas fa-cog"></i> Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($epargnes)): ?>
              <tr>
                <td colspan="8" class="no-results">
                  <i class="fas fa-info-circle"></i> Aucune épargne enregistrée
                </td>
              </tr>
            <?php else: ?>
              <?php foreach ($epargnes as $e): ?>
                <?php
                  $compte = array_filter($comptes, fn($c) => $c['id_compte'] == $e['id_compte']);
                  $nom_compte = $compte ? reset($compte)['nom_compte'] : 'Compte inconnu';
                  $progression = ($e['montant_vise'] > 0) ? round(($e['montant_actuel'] / $e['montant_vise']) * 100) : 0;
                ?>
                <tr>
                  <td><?= htmlspecialchars($e['libelle_epargne']) ?></td>
                  <td><?= htmlspecialchars($e['objectif']) ?></td>
                  <td><?= htmlspecialchars($nom_compte) ?></td>
                  <td><?= number_format($e['montant_vise'], 0, ',', ' ') ?> FCFA</td>
                  <td><?= number_format($e['montant_actuel'], 0, ',', ' ') ?> FCFA</td>
                  <td>
                    <div style="display: flex; align-items: center; gap: 8px;">
                      <span><?= $progression ?>%</span>
                      <div class="progress-container">
                        <div class="progress-bar" style="width: <?= min($progression, 100) ?>%"></div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <?php
                      $statut = $e['statut'];
                      $badgeClass = 'badge-danger';
                      if ($statut === 'atteint') {
                        $badgeClass = 'badge-success';
                      } elseif ($statut === 'en_cours') {
                        $badgeClass = 'badge-warning';
                      }
                    ?>
                    <span class="badge <?= $badgeClass ?>">
                      <?= ucfirst(str_replace('_', ' ', $e['statut'])) ?>
                    </span>
                  </td>
                  <td class="actions">
                    <a href="../index.php/edit_epargne_ct/<?= $e['id_epargne_ct'] ?>" class="btn btn-primary btn-sm" title="Modifier">
                      <i class="fas fa-edit"></i>
                    </a>
                    <form method="POST" action="../index.php/delete_epargne_ct/<?= $e['id_epargne_ct'] ?>" onsubmit="return confirm('Supprimer cette épargne ?');" 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>