<?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>Modification financement de dépense - 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, h3 {
      color: #343a40; /* Couleur fin_dep du dashboard */
      margin-top: 0;
    }

    h2 {
      background-color: #343a40;
      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"],
    input[type="time"],
    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: #343a40;
      outline: none;
      box-shadow: 0 0 0 3px rgba(52,58,64,0.1);
    }

    /* 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 : 10px;
    }

    .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: #343a40;
      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: #343a40;
      color: white;
      font-weight: 500;
    }

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

    /* Total disponible */
    .total-disponible {
      font-weight: bold;
      padding: 10px;
      background-color: #e9ecef;
      border-radius: 5px;
      margin: 15px 0;
    }

    /* Feedback */
    .feedback {
      color: #dc3545;
      font-size: 14px;
      margin-top: 5px;
    }

    /* 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-edit"></i> Modifier financement de dépense</h2>

  <div class="container">
    <!-- Section de modification -->
    <div class="card">
      <h3 style="color: #343a40;"><i class="fas fa-pencil-alt"></i> Modifier le financement</h3>
      
      <?php if (isset($alertClass)): ?>
        <div class="alert <?= $alertClass ?>">
          <i class="fas <?= $icon ?>"></i> <?= $flashMessage ?>
        </div>
      <?php endif; ?>

      <form method="POST" action="../update_financement_depense/<?= $financement['id_financer'] ?>">
        <div class="form-group">
          <label><i class="fas fa-tag"></i> Libellé :</label>
          <input type="text" name="libelle_financement" value="<?= htmlspecialchars($financement['libelle_financement']) ?>" required>
        </div>

        <div class="form-group">
          <label><i class="fas fa-money-bill-wave"></i> Dépense à financer :</label>
          <select name="id_depense">
            <option value="">-- Sélectionnez la dépense à financer --</option>
            <?php foreach ($depenses as $d): ?>
              <option value="<?= $d['id_depense'] ?>" <?= ($d['id_depense'] == $financement['id_depense']) ? 'selected' : '' ?>>
                <?= htmlspecialchars($d['libelles_depenses']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-hand-holding-usd"></i> Revenu :</label>
          <select name="id_revenu" id="revenuSelect">
            <option value="">-- Sélectionnez un revenu --</option>
            <?php foreach ($revenus as $r): ?>
              <option value="<?= $r['id_revenu'] ?>" data-montant="<?= $r['montant'] ?>" <?= ($r['id_revenu'] == $financement['id_revenu']) ? 'selected' : '' ?>>
                <?= htmlspecialchars($r['libelle_revenu']) ?> (<?= number_format($r['montant'], 0, ',', ' ') ?> FCFA)
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-coins"></i> Gain :</label>
          <select name="id_gain" id="gainSelect">
            <option value="">-- Sélectionnez un gain complémentaire --</option>
            <?php foreach ($gains as $g): ?>
              <option value="<?= $g['id_gain'] ?>" data-montant="<?= $g['montant_gain'] ?>" <?= ($g['id_gain'] == $financement['id_gain']) ? 'selected' : '' ?>>
                <?= htmlspecialchars($g['libelle_gain']) ?> (<?= number_format($g['montant_gain'], 0, ',', ' ') ?> FCFA)
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="total-disponible" id="totalDisponible">
          <i class="fas fa-wallet"></i> Total disponible : 
          <?= number_format(($financement['montant_revenu'] ?? 0) + ($financement['montant_gain'] ?? 0), 0, ',', ' ') ?> FCFA
        </div>

        <div class="form-group">
          <label><i class="fas fa-money-bill-wave"></i> Montant :</label>
          <input type="number" name="montant_f" step="0.01" value="<?= $financement['montant_f'] ?>" required>
          <div class="feedback" id="montantFeedback"></div>
        </div>

        <div class="form-group">
          <label><i class="fas fa-calendar-day"></i> Date :</label>
          <input type="date" name="date_financer" value="<?= $financement['date_financer'] ?>">
        </div>

        <div class="form-group">
          <label><i class="fas fa-clock"></i> Heure :</label>
          <input type="time" name="heure_financer" value="<?= $financement['heure_financer'] ?>">
        </div>

        <div class="form-group">
          <label><i class="fas fa-list"></i> Type :</label>
          <select name="type_financement">
            <option value="Direct" <?= ($financement['type_financement'] == 'Direct') ? 'selected' : '' ?>>Direct</option>
            <option value="Indirect" <?= ($financement['type_financement'] == 'Indirect') ? 'selected' : '' ?>>Indirect</option>
            <option value="Mixte" <?= ($financement['type_financement'] == 'Mixte') ? 'selected' : '' ?>>Mixte</option>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-bullseye"></i> Objectif :</label>
          <select name="objectif_financement">
            <?php
              $objectifs = ['Logement','Education','Loisir','Investissement','Urgent','Régularisation','Nutrition','Énergie','Transport','Communication','Autre','Social extérieur','Social famille'];
              foreach ($objectifs as $obj): ?>
                <option value="<?= $obj ?>" <?= ($financement['objectif_financement'] == $obj) ? 'selected' : '' ?>><?= $obj ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-calendar-alt"></i> Durée :</label>
          <select name="duree_financement">
            <option value="Ponctuel" <?= ($financement['duree_financement'] == 'Ponctuel') ? 'selected' : '' ?>>Ponctuel</option>
            <option value="Journalier" <?= ($financement['duree_financement'] == 'Journalier') ? 'selected' : '' ?>>Journalier</option>
            <option value="Hebdomadaire" <?= ($financement['duree_financement'] == 'Hebdomadaire') ? 'selected' : '' ?>>Hebdomadaire</option>
            <option value="Mensuel" <?= ($financement['duree_financement'] == 'Mensuel') ? 'selected' : '' ?>>Mensuel</option>
            <option value="Trimestriel" <?= ($financement['duree_financement'] == 'Trimestriel') ? 'selected' : '' ?>>Trimestriel</option>
            <option value="Annuel" <?= ($financement['duree_financement'] == 'Annuel') ? 'selected' : '' ?>>Annuel</option>
            <option value="Autre" <?= ($financement['duree_financement'] == 'Autre') ? 'selected' : '' ?>>Autre</option>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-chart-line"></i> Impact :</label>
          <select name="impact_financier">
            <option value="Réduction_dépenses" <?= ($financement['impact_financier'] == 'Réduction_dépenses') ? 'selected' : '' ?>>Réduction_dépenses</option>
            <option value="Augmentation_rendement" <?= ($financement['impact_financier'] == 'Augmentation_rendement') ? 'selected' : '' ?>>Augmentation_rendement</option>
            <option value="Rééquilibrage" <?= ($financement['impact_financier'] == 'Rééquilibrage') ? 'selected' : '' ?>>Rééquilibrage</option>
            <option value="Stabilisation" <?= ($financement['impact_financier'] == 'Stabilisation') ? 'selected' : '' ?>>Stabilisation</option>
            <option value="Dépense faible" <?= ($financement['impact_financier'] == 'Dépense faible') ? 'selected' : '' ?>>Dépense faible</option>
            <option value="Dépense moyen" <?= ($financement['impact_financier'] == 'Dépense moyen') ? 'selected' : '' ?>>Dépense moyen</option>
            <option value="Dépense forte" <?= ($financement['impact_financier'] == 'Dépense forte') ? 'selected' : '' ?>>Dépense forte</option>
            <option value="Autre" <?= ($financement['impact_financier'] == 'Autre') ? 'selected' : '' ?>>Autre</option>
            <option value="Aucun" <?= ($financement['impact_financier'] == 'Aucun') ? 'selected' : '' ?>>Aucun</option>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-project-diagram"></i> Méthode d'allocation :</label>
          <select name="methode_allocation">
            <option value="Prioritaire" <?= ($financement['methode_allocation'] == 'Prioritaire') ? 'selected' : '' ?>>Prioritaire</option>
            <option value="Equilibrée" <?= ($financement['methode_allocation'] == 'Equilibrée') ? 'selected' : '' ?>>Equilibrée</option>
            <option value="Aléatoire" <?= ($financement['methode_allocation'] == 'Aléatoire') ? 'selected' : '' ?>>Aléatoire</option>
            <option value="Planifiée" <?= ($financement['methode_allocation'] == 'Planifiée') ? 'selected' : '' ?>>Planifiée</option>
          </select>
        </div>

        <div>
          <button type="submit" class="btn btn-primary">
            <i class="fas fa-save"></i> Mettre à jour
          </button>
          <a href="../financements_depenses" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Retour à la liste
          </a>
          <a href="../dashboard" class="btn btn-secondary">
            <i class="fas fa-tachometer-alt"></i> Tableau de bord
          </a>
        </div>
      </form>
    </div>
  </div>

  <script>
    // Gestion du total disponible
    function updateTotalDisponible() {
      const revenu = parseFloat(document.getElementById("revenuSelect").selectedOptions[0]?.dataset.montant || 0);
      const gain = parseFloat(document.getElementById("gainSelect").selectedOptions[0]?.dataset.montant || 0);
      const total = revenu + gain;
      document.getElementById("totalDisponible").innerHTML = 
        `<i class="fas fa-wallet"></i> Total disponible : ${total.toLocaleString()} FCFA`;
    }

    // Validation du montant
    function validateMontant() {
      const montant = parseFloat(document.querySelector("input[name='montant_f']").value || 0);
      const total = parseFloat(document.getElementById("revenuSelect").selectedOptions[0]?.dataset.montant || 0) + 
                   parseFloat(document.getElementById("gainSelect").selectedOptions[0]?.dataset.montant || 0);
      const feedback = document.getElementById("montantFeedback");

      if (montant > total) {
        feedback.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Montant supérieur au total disponible';
        return false;
      } else {
        feedback.textContent = '';
        return true;
      }
    }

    // Écouteurs d'événements
    document.getElementById("revenuSelect").addEventListener("change", function() {
      updateTotalDisponible();
      validateMontant();
    });

    document.getElementById("gainSelect").addEventListener("change", function() {
      updateTotalDisponible();
      validateMontant();
    });

    document.querySelector("input[name='montant_f']").addEventListener("input", validateMontant);

    // Validation du formulaire
    document.querySelector("form").addEventListener("submit", function(e) {
      if (!validateMontant()) {
        e.preventDefault();
      } else {
        this.querySelector("button[type='submit']").disabled = true;
      }
    });

    // Initialisation
    updateTotalDisponible();
  </script>
</body>
</html>