<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Modifier une dépense - 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" />
  <link rel="stylesheet" type="text/css" id="theme" href="../../css/theme-default.css"/>
  <style>
    body {
      margin: 0;
      font-family: 'Segoe UI', sans-serif;
      background-color: #f4f6f8;
      color: #333;
    }
    h2 {
      background-color: #dc3545;
      color: white;
      padding: 20px;
      margin: 0;
      text-align: center;
      font-size: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
    }
    .container {
      max-width: 1000px;
      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;
    }
    .form-group {
      margin-bottom: 20px;
    }
    .form-group label {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
      font-weight: 500;
      color: #555;
    }
    input[type="text"],
    input[type="number"],
    input[type="date"],
    select,
    textarea {
      width: 100%;
      padding: 12px 15px;
      border: 1px solid #ddd;
      border-radius: 8px;
      font-size: 16px;
      transition: all 0.3s;
      background-color: #f8f9fa;
    }
    input:focus,
    select:focus,
    textarea:focus {
      border-color: #dc3545;
      outline: none;
      box-shadow: 0 0 0 3px rgba(220, 53, 69, 0.2);
      background-color: white;
    }
    textarea {
      min-height: 100px;
      resize: vertical;
    }
    .btn-group {
      display: flex;
      gap: 15px;
      margin-top: 25px;
    }
    .btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 12px 20px;
      border-radius: 8px;
      text-decoration: none;
      font-weight: bold;
      border: none;
      cursor: pointer;
      font-size: 16px;
      transition: all 0.3s;
    }
    .btn-primary {
      background-color: #dc3545;
      color: white;
    }
    .btn-secondary {
      background-color: #6c757d;
      color: white;
    }
    .btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    }
    select {
      -webkit-appearance: none;
      -moz-appearance: none;
      appearance: none;
      background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
      background-repeat: no-repeat;
      background-position: right 10px center;
      background-size: 15px;
      padding-right: 35px !important;
    }
    @media (max-width: 768px) {
      .container {
        padding: 0 15px;
      }
      .btn-group {
        flex-direction: column;
      }
      .btn {
        width: 100%;
      }
    }
    .notification {
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 15px 25px;
      border-radius: 8px;
      color: white;
      z-index: 1000;
      display: flex;
      align-items: center;
      gap: 10px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      opacity: 0;
      transition: opacity 0.5s;
    }
    .notification.show {
      opacity: 1;
    }
    .notification-success {
      background-color: #28a745;
    }
    .notification-error {
      background-color: #e74c3c;
    }
  </style>
</head>
<body>
  <?php if (session_status() === PHP_SESSION_NONE) session_start(); ?>

  <?php if (isset($_SESSION['flash'])): ?>
    <div class="notification notification-<?= $_SESSION['flash']['type'] ?> show" id="notification">
      <i class="fas <?= $_SESSION['flash']['type'] === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?>"></i>
      <span><?= $_SESSION['flash']['message'] ?></span>
    </div>
    <?php unset($_SESSION['flash']); ?>
  <?php endif; ?>

  <h2><i class="fas fa-money-bill-wave"></i> Modifier une dépense</h2>
  
  <div class="container">
    <div class="card">
      <form method="POST" action="../update_depense/<?= $depense['id_depense'] ?>">
        <input type="hidden" name="id_faiseur" value="<?= $_SESSION['user']['id_utilisateur'] ?>">

        <div class="form-group">
          <label><i class="fas fa-tag"></i> Libellé :</label>
          <input type="text" name="libelles_depenses" value="<?= htmlspecialchars($depense['libelles_depenses'] ?? '') ?>" required>
        </div>

        <div class="form-group">
          <label><i class="fas fa-layer-group"></i> Catégorie :</label>
          <select name="categories" required>
            <?php
              $categories = [
                'Vie_courante_et_besoins_essentiels' => 'Vie courante',
                'Activite_professionnelle_ou_business' => 'Activité professionnelle',
                'Engagements_financiers' => 'Engagements financiers',
                'Depenses_sociales_ou_personnelles' => 'Dépenses personnelles',
                'Projets_et_investissements' => 'Projets',
                'Institutionnel_et_reglementaire' => 'Institutionnel'
              ];
              foreach ($categories as $value => $label) {
                $selected = ($depense['categories'] ?? '') === $value ? 'selected' : '';
                echo "<option value=\"$value\" $selected>$label</option>";
              }
            ?>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-tags"></i> Sous-catégorie :</label>
          <select name="sous_categories" required>
            <?php
              $sousCats = [
                'Logement', 'Alimentation', 'Transport', 'Santé', 'Éducation',
                'Fournitures pro', 'Communication', 'Déplacement pro', 'Salaires',
                'Remboursement dette', 'Versement épargne', 'Assurance', 'Loisirs',
                'Cadeaux', 'Cérémonie', 'Habits', 'Immobilier', 'Inversement',
                'Maintenance', 'Impôt taxes', 'Frais administratifs', 'Cotisation',
                'Energie électrique'
              ];
              foreach ($sousCats as $sc) {
                $selected = ($depense['sous_categories'] ?? '') === $sc ? 'selected' : '';
                echo "<option value=\"$sc\" $selected>$sc</option>";
              }
            ?>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-list"></i> Type de dépense :</label>
          <select name="type_depense" required>
            <option value="Fixe" <?= ($depense['type_depense'] ?? '') === 'Fixe' ? 'selected' : '' ?>>Fixe</option>
            <option value="Variable" <?= ($depense['type_depense'] ?? '') === 'Variable' ? 'selected' : '' ?>>Variable</option>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-calendar-alt"></i> Périodicité :</label>
          <select name="periodicite" required>
            <?php
              $periods = [
                'Journalière', 'Hebdomadaire', 'Mensuelle', 
                'Trimestrielle', 'Semestrielle', 'Annuelle', 'Alternative'
              ];
              foreach ($periods as $p) {
                $selected = ($depense['periodicite'] ?? '') === $p ? 'selected' : '';
                echo "<option value=\"$p\" $selected>$p</option>";
              }
            ?>
          </select>
        </div>

        <div class="form-group">
            <label><i class="fas fa-credit-card"></i> Mode de paiement :</label>
            <select name="mode_paiement"  title="Sélectionnez le mode de paiement utilisé" required>
                <option value="">-- Sélectionnez un mode de paiement --</option>
                <option value="Espèces" <?= ($depense['mode_paiement'] ?? '') === 'Espèces' ? 'selected' : '' ?>>💰 Espèces</option>
                <option value="Carte bancaire" <?= ($depense['mode_paiement'] ?? '') === 'Carte bancaire' ? 'selected' : '' ?>>💳 Carte bancaire</option>
                <option value="Chèque" <?= ($depense['mode_paiement'] ?? '') === 'Chèque' ? 'selected' : '' ?>>📝 Chèque</option>
                <option value="Virement" <?= ($depense['mode_paiement'] ?? '') === 'Virement' ? 'selected' : '' ?>>↔️ Virement</option>
                <option value="Prélèvement" <?= ($depense['mode_paiement'] ?? '') === 'Prélèvement' ? 'selected' : '' ?>>🔄 Prélèvement</option>
                <option value="Mobile Payment" <?= ($depense['mode_paiement'] ?? '') === 'Mobile Payment' ? 'selected' : '' ?>>📱 Mobile Payment</option>
                <option value="Crypto" <?= ($depense['mode_paiement'] ?? '') === 'Crypto' ? 'selected' : '' ?>>🪙 Crypto</option>
                <option value="Carte cadeau" <?= ($depense['mode_paiement'] ?? '') === 'Carte cadeau' ? 'selected' : '' ?>>🎁 Carte cadeau</option>
                <option value="Virement instantané" <?= ($depense['mode_paiement'] ?? '') === 'Virement instantané' ? 'selected' : '' ?>>⚡ Virement instantané</option>
                <option value="Portefeuille électronique" <?= ($depense['mode_paiement'] ?? '') === 'Portefeuille électronique' ? 'selected' : '' ?>>👛 Portefeuille électronique</option>
                <option value="Autre" <?= ($depense['mode_paiement'] ?? '') === 'Autre' ? 'selected' : '' ?>>❓ Autre</option>
            </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-coins"></i> Montant périodique :</label>
          <input type="number" name="montant_periodique" step="0.01" 
                 value="<?= htmlspecialchars($depense['montant_periodique'] ?? '') ?>" required>
        </div>

        <div class="form-group">
          <label><i class="fas fa-calculator"></i> Montant annuel estimatif :</label>
          <input type="number" name="montant_annuel_estimatif" step="0.01" 
                 value="<?= htmlspecialchars($depense['montant_annuel_estimatif'] ?? '') ?>">
        </div>

        <div class="form-group">
          <label><i class="fas fa-calendar-day"></i> Date prévue :</label>
          <input type="date" name="date_prevu_depense" 
                 value="<?= htmlspecialchars($depense['date_prevu_depense'] ?? '') ?>" required>
        </div>

        <div class="form-group">
          <label><i class="fas fa-calendar-times"></i> Date d'échéance :</label>
          <input type="date" name="date_echeance" 
                 value="<?= htmlspecialchars($depense['date_echeance'] ?? '') ?>">
        </div>

        <div class="form-group">
          <label><i class="fas fa-info-circle"></i> Statut :</label>
          <select name="statut_depense" required>
            <option value="Prévue" <?= ($depense['statut_depense'] ?? '') === 'Prévue' ? 'selected' : '' ?>>Prévue</option>
            <option value="Réalisée" <?= ($depense['statut_depense'] ?? '') === 'Réalisée' ? 'selected' : '' ?>>Réalisée</option>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-user-tie"></i> Bénéficiaire :</label>
          <select name="id_receveur" required>
            <option value="">Sélectionnez un bénéficiaire</option>
            <?php foreach ($utilisateurs as $u): ?>
              <option value="<?= $u['id_utilisateur'] ?>" 
                <?= ($depense['id_receveur'] ?? '') == $u['id_utilisateur'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($u['nom'] ?? '') ?> <?= htmlspecialchars($u['prenom'] ?? '') ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-user-check"></i> Responsable validation :</label>
          <select name="responsable_validation">
            <option value="">Sélectionnez un responsable</option>
            <?php foreach ($utilisateurs as $u): ?>
              <option value="<?= $u['id_utilisateur'] ?>" 
                <?= ($depense['responsable_validation'] ?? '') == $u['id_utilisateur'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($u['nom'] ?? '') ?> <?= htmlspecialchars($u['prenom'] ?? '') ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-chart-line"></i> Impact budgétaire :</label>
          <select name="impact_budgetaire" required>
            <option value="Faible" <?= ($depense['impact_budgetaire'] ?? '') === 'Faible' ? 'selected' : '' ?>>Faible</option>
            <option value="Moyen" <?= ($depense['impact_budgetaire'] ?? '') === 'Moyen' ? 'selected' : '' ?>>Moyen</option>
            <option value="Fort" <?= ($depense['impact_budgetaire'] ?? '') === 'Fort' ? 'selected' : '' ?>>Fort</option>
          </select>
        </div>

        <div class="form-group">
          <label><i class="fas fa-align-left"></i> Description :</label>
          <textarea name="description"><?= htmlspecialchars($depense['description'] ?? '') ?></textarea>
        </div>

        <div class="form-group">
          <label><i class="fas fa-file-alt"></i> Pièce justificative :</label>
          <textarea name="piece_justificative"><?= htmlspecialchars($depense['piece_justificative'] ?? '') ?></textarea>
        </div>

        <div class="btn-group">
          <button type="submit" class="btn btn-primary">
            <i class="fas fa-save"></i> Enregistrer
          </button>
          <a href="../depenses" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Annuler
          </a>
        </div>
      </form>
    </div>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // Gestion de la notification
      const notification = document.getElementById('notification');
      if (notification) {
        setTimeout(() => {
          notification.classList.remove('show');
          setTimeout(() => notification.remove(), 500);
        }, 5000);
      }
      
      // Calcul automatique du montant annuel
      const periodiciteSelect = document.querySelector('select[name="periodicite"]');
      const montantPeriodique = document.querySelector('input[name="montant_periodique"]');
      const montantAnnuel = document.querySelector('input[name="montant_annuel_estimatif"]');
      
      function calculateAnnualAmount() {
        if (!periodiciteSelect.value || !montantPeriodique.value) return;
        
        const amount = parseFloat(montantPeriodique.value);
        if (isNaN(amount)) return;
        
        let multiplier;
        switch (periodiciteSelect.value) {
          case 'Journalière': multiplier = 365; break;
          case 'Hebdomadaire': multiplier = 52; break;
          case 'Mensuelle': multiplier = 12; break;
          case 'Trimestrielle': multiplier = 4; break;
          case 'Semestrielle': multiplier = 2; break;
          case 'Annuelle': multiplier = 1; break;
          default: multiplier = 1;
        }
        
        montantAnnuel.value = (amount * multiplier).toFixed(2);
      }
      
      periodiciteSelect.addEventListener('change', calculateAnnualAmount);
      montantPeriodique.addEventListener('input', calculateAnnualAmount);
      
      // Calcul initial au chargement
      calculateAnnualAmount();
    });
  </script>
</body>
</html>