<?php 
session_start();
$userprofil = $_SESSION['user'];
if ($userprofil == true) {
    include('includes/header.php');
    require_once "includes/dbconn.php";
} else {
    header("Location: login.php");
    exit();
}

// Traitement suppression AJAX
if (isset($_POST['action']) && $_POST['action'] === 'delete') {
    $id = (int)$_POST['id'];
    $stmt = $conn->prepare("DELETE FROM lettres_reglement WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    exit('deleted');
}

// Traitement mise à jour AJAX
if (isset($_POST['action']) && $_POST['action'] === 'update') {
    $id = (int)$_POST['id'];
    $date = $_POST['date'];
    $montant = floatval($_POST['montant']);
    $stmt = $conn->prepare("UPDATE lettres_reglement SET date_reglement = ?, montant = ? WHERE id = ?");
    $stmt->bind_param("sdi", $date, $montant, $id);
    $stmt->execute();
    exit('updated');
}

// Traitement filtre
$from = $_GET['from'] ?? '';
$to = $_GET['to'] ?? '';
$where = "1=1";
$params = [];
$types = '';

if ($from) {
    $where .= " AND date_reglement >= ?";
    $params[] = $from; $types .= 's';
}
if ($to) {
    $where .= " AND date_reglement <= ?";
    $params[] = $to; $types .= 's';
}

$sql = "SELECT * FROM lettres_reglement WHERE $where ORDER BY date_reglement DESC";
$stmt = $conn->prepare($sql);
if ($params) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$lettres = $result->fetch_all(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Liste des lettres de règlement</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <style>
    :root {
      --bordeaux: #800020;
      --bordeaux-light: #a3436a;
      --bordeaux-dark: #5c0013;
      --gold: #d4af37;
      --cream: #f8f4e9;
    }
    
    body {
      background-color: var(--cream);
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    .container {
      max-width: 95%;
      margin-top: 2rem;
    }
    
    .page-title {
      color: var(--bordeaux);
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: 1px;
      border-bottom: 2px solid var(--gold);
      padding-bottom: 0.5rem;
      margin-bottom: 2rem;
    }
    
    .filter-card {
      background: white;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
      padding: 1.5rem;
      margin-bottom: 2rem;
      border-top: 4px solid var(--bordeaux);
    }
    
    .btn-primary {
      background-color: var(--bordeaux);
      border-color: var(--bordeaux-dark);
    }
    
    .btn-primary:hover {
      background-color: var(--bordeaux-dark);
      border-color: var(--bordeaux-dark);
    }
    
    .btn-success {
      background-color: var(--gold);
      border-color: #c19a2b;
      color: #333;
    }
    
    .btn-success:hover {
      background-color: #c19a2b;
      border-color: #a88729;
    }
    
    .table-container {
      background: white;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
      overflow: hidden;
      padding: 0;
    }
    
    .table {
      margin-bottom: 0;
    }
    
    .table thead {
      background-color: var(--bordeaux);
      color: white;
    }
    
    .table th {
      font-weight: 600;
      text-transform: uppercase;
      font-size: 0.85rem;
      letter-spacing: 0.5px;
    }
    
    .table tbody tr:hover {
      background-color: rgba(128, 0, 32, 0.05);
    }
    
    .btn-sm {
      font-size: 0.8rem;
      padding: 0.25rem 0.5rem;
    }
    
    .btn-warning {
      background-color: var(--gold);
      border-color: #c19a2b;
      color: #333;
    }
    
    .btn-danger {
      background-color: #dc3545;
      border-color: #dc3545;
    }
    
    .empty-state {
      padding: 2rem;
      text-align: center;
      color: #666;
    }
    
    .empty-state i {
      font-size: 2rem;
      color: #ddd;
      margin-bottom: 1rem;
    }
  </style>
</head>
<body>
<div class="container">
  <h1 class="page-title"><i class="fas fa-file-invoice me-2"></i>Lettres de Règlement</h1>

  <div class="filter-card">
    <form method="get" class="row g-3">
      <div class="col-md-4">
        <label class="form-label fw-bold">Du :</label>
        <input type="date" name="from" value="<?= htmlspecialchars($from) ?>" class="form-control">
      </div>
      <div class="col-md-4">
        <label class="form-label fw-bold">Au :</label>
        <input type="date" name="to" value="<?= htmlspecialchars($to) ?>" class="form-control">
      </div>
      <div class="col-md-4 d-flex align-items-end">
        <button class="btn btn-primary me-2"><i class="fas fa-filter me-1"></i> Filtrer</button>
        <a href="lettres_reglement.php" class="btn btn-success"><i class="fas fa-sync-alt me-1"></i> Réinitialiser</a>
      </div>
    </form>
  </div>

  <div class="table-container">
    <table class="table table-hover">
      <thead>
        <tr>
          <th>ID</th>
          <th>Date</th>
          <th>Objet</th>
          <th>Nom complet</th>
          <th>Montant (F CFA)</th>
          <th>CN</th>
          <th>Libellé</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php if (!$lettres): ?>
        <tr>
          <td colspan="8" class="empty-state">
            <i class="far fa-file-alt"></i>
            <p class="mt-2">Aucune lettre trouvée</p>
          </td>
        </tr>
      <?php else: foreach ($lettres as $l): ?>
        <tr id="row-<?= $l['id'] ?>">
          <td><?= $l['id'] ?></td>
          <td><?= date('d/m/Y', strtotime($l['date_reglement'])) ?></td>
          <td><?= htmlspecialchars($l['objet']) ?></td>
          <td><?= htmlspecialchars($l['nom_complet']) ?></td>
          <td><?= number_format($l['montant'], 2, ',', ' ') ?></td>
          <td><?= htmlspecialchars($l['cn']) ?></td>
          <td><?= htmlspecialchars($l['libelle']) ?></td>
          <td>
            <button class="btn btn-sm btn-warning me-1" onclick="modifierLettre(<?= $l['id'] ?>, '<?= $l['date_reglement'] ?>', <?= $l['montant'] ?>)">
              <i class="fas fa-edit"></i>
            </button>
            <button class="btn btn-sm btn-danger" onclick="supprimerLettre(<?= $l['id'] ?>)">
              <i class="fas fa-trash-alt"></i>
            </button>
          </td>
        </tr>
      <?php endforeach; endif ?>
      </tbody>
    </table>
  </div>
</div>

<script>
function supprimerLettre(id) {
  Swal.fire({
    title: 'Confirmer la suppression',
    text: "Cette action est irréversible. Voulez-vous continuer ?",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#800020',
    cancelButtonColor: '#6c757d',
    confirmButtonText: 'Oui, supprimer',
    cancelButtonText: 'Annuler',
    backdrop: 'rgba(0,0,0,0.4)'
  }).then(result => {
    if (result.isConfirmed) {
      fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ action: 'delete', id })
      }).then(() => {
        document.getElementById('row-' + id).remove();
        Swal.fire({
          title: 'Supprimé !',
          text: 'La lettre a été supprimée avec succès.',
          icon: 'success',
          confirmButtonColor: '#800020'
        });
      });
    }
  });
}

function modifierLettre(id, currentDate, currentMontant) {
  Swal.fire({
    title: 'Modifier la lettre',
    html:
      `<div class="mb-3">
        <label class="form-label">Date</label>
        <input type="date" id="date" class="form-control" value="${currentDate}">
      </div>
      <div class="mb-3">
        <label class="form-label">Montant (F CFA)</label>
        <input type="number" id="montant" class="form-control" step="0.01" value="${currentMontant}">
      </div>`,
    focusConfirm: false,
    showCancelButton: true,
    confirmButtonText: 'Enregistrer',
    confirmButtonColor: '#800020',
    cancelButtonColor: '#6c757d',
    backdrop: 'rgba(0,0,0,0.4)',
    preConfirm: () => {
      const date = document.getElementById('date').value;
      const montant = document.getElementById('montant').value;
      if (!date || !montant) {
        Swal.showValidationMessage('Veuillez remplir tous les champs');
        return false;
      }

      return fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          action: 'update',
          id: id,
          date: date,
          montant: montant
        })
      }).then(() => {
        Swal.fire({
          title: 'Modifié !',
          text: 'Les modifications ont été enregistrées.',
          icon: 'success',
          confirmButtonColor: '#800020'
        }).then(() => location.reload());
      });
    }
  });
}
</script>
</body>
</html>