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

if (isset($_GET['matricule'])) {
    $mat = mysqli_real_escape_string($conn, $_GET['matricule']);
    $res = mysqli_query($conn, "SELECT prenom, noms FROM etudiants WHERE matricule = '$mat' LIMIT 1");
    if ($res && mysqli_num_rows($res) > 0) {
        $etu = mysqli_fetch_assoc($res);
        echo json_encode(['success' => true, 'prenom' => $etu['prenom'], 'noms' => $etu['noms']]);
    } else {
        echo json_encode(['success' => false]);
    }
    exit;
}

$redirectId = null;
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $matricule = trim($_POST['matricule'] ?? '');
    $mois = trim($_POST['mois'] ?? '');
    $montant = trim($_POST['montant'] ?? '');
    $date_paiement = $_POST['date_paiement'] ?? '';
    $mode_paiement = $_POST['mode_paiement'] ?? '';
    $commentaire = trim($_POST['commentaire'] ?? '');

    if (!$matricule || !$mois || !$montant || !$date_paiement || !$mode_paiement) {
        $error = "Tous les champs obligatoires doivent être remplis.";
    } else {
        $res = mysqli_query($conn, "SELECT id FROM etudiants WHERE matricule = '".mysqli_real_escape_string($conn, $matricule)."' LIMIT 1");
        if ($res && mysqli_num_rows($res) > 0) {
            $etu = mysqli_fetch_assoc($res);
            $etudiant_id = $etu['id'];

            $query = "INSERT INTO mensualites (etudiant_id, mois, montant, date_paiement, mode_paiement, commentaire)
                      VALUES ('$etudiant_id', '$mois', '$montant', '$date_paiement', '$mode_paiement', '$commentaire')";
            if (mysqli_query($conn, $query)) {
                $redirectId = mysqli_insert_id($conn);
            } else {
                $error = "Erreur lors de l'enregistrement.";
            }
        } else {
            $error = "Matricule étudiant introuvable.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8" />
  <title>Paiement Mensualité</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <style>
    body {
      background-color: #f8f9fa;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    .card {
      max-width: 750px;
      margin: 30px auto;
      border-radius: 12px;
      box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
      border: none;
      overflow: hidden;
    }
    .card-header {
      background: linear-gradient(135deg, #1a5276, #27ae60);
      color: white;
      padding: 20px;
      border-bottom: none;
    }
    .card-body {
      padding: 30px;
    }
    .form-label {
      font-weight: 600;
      color: #1a5276;
      margin-bottom: 8px;
    }
    .form-control, .form-select {
      border-radius: 8px;
      padding: 10px 15px;
      border: 1px solid #ced4da;
      transition: all 0.3s;
    }
    .form-control:focus, .form-select:focus {
      border-color: #1a5276;
      box-shadow: 0 0 0 0.25rem rgba(26, 82, 118, 0.25);
    }
    .btn-primary {
      background: linear-gradient(to right, #1a5276, #2980b9);
      border: none;
      border-radius: 8px;
      padding: 12px;
      font-weight: 600;
      letter-spacing: 0.5px;
      transition: all 0.3s;
    }
    .btn-primary:hover {
      background: linear-gradient(to right, #154360, #1a5276);
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    .alert {
      border-radius: 8px;
    }
    .required-field::after {
      content: " *";
      color: #e74c3c;
    }
    .input-group-text {
      background-color: #f1f8fe;
      color: #1a5276;
      font-weight: 600;
    }
  </style>
</head>
<body>
  <div class="card">
    <div class="card-header text-center">
      <h2 class="mb-0 fw-bold">Paiement Mensualité</h2>
    </div>
    
    <div class="card-body">
      <?php if (!empty($error)): ?>
        <div class="alert alert-danger text-center"><?= htmlspecialchars($error) ?></div>
      <?php endif; ?>

      <form id="paiementForm" method="POST" novalidate>
        <div class="row mb-4">
          <div class="col-md-6 mb-3">
            <label for="matricule" class="form-label required-field">Matricule</label>
            <input type="text" class="form-control" id="matricule" name="matricule" required autocomplete="off" />
          </div>
          <div class="col-md-6 mb-3">
            <label for="prenom" class="form-label">Prénom</label>
            <input type="text" class="form-control" id="prenom" name="prenom" readonly />
          </div>
        </div>

        <div class="row mb-4">
          <div class="col-md-6 mb-3">
            <label for="noms" class="form-label">Noms</label>
            <input type="text" class="form-control" id="noms" name="noms" readonly />
          </div>
          <div class="col-md-6 mb-3">
            <label for="mois" class="form-label required-field">Mois</label>
            <input type="text" class="form-control" id="mois" name="mois" required />
          </div>
        </div>

        <div class="row mb-4">
          <div class="col-md-6 mb-3">
            <label for="montant" class="form-label required-field">Montant</label>
            <div class="input-group">
              <input type="number" min="0" step="100" class="form-control" id="montant" name="montant" required />
              <span class="input-group-text">XOF</span>
            </div>
          </div>
          <div class="col-md-6 mb-3">
            <label for="date_paiement" class="form-label required-field">Date de paiement</label>
            <input type="date" class="form-control" id="date_paiement" name="date_paiement" required />
          </div>
        </div>

        <div class="row mb-4">
          <div class="col-md-6 mb-3">
            <label for="mode_paiement" class="form-label required-field">Mode de paiement</label>
            <select class="form-select" id="mode_paiement" name="mode_paiement" required>
              <option value="" selected disabled>Choisir...</option>
              <option>Espèces</option>
              <option>Mobile Money</option>
              <option>Virement</option>
            </select>
          </div>
          <div class="col-md-6 mb-3">
            <label for="commentaire" class="form-label">Commentaire</label>
            <input type="text" class="form-control" id="commentaire" name="commentaire" placeholder="Optionnel" />
          </div>
        </div>

        <div class="d-grid mt-4">
          <button type="submit" class="btn btn-primary btn-lg" id="submitBtn">
            <i class="fas fa-save me-2"></i>Enregistrer le paiement
          </button>
        </div>
      </form>
    </div>
  </div>

  <script>
    const form = document.getElementById('paiementForm');
    const matriculeInput = document.getElementById('matricule');
    const prenomInput = document.getElementById('prenom');
    const nomsInput = document.getElementById('noms');
    const submitBtn = document.getElementById('submitBtn');

    // Auto-remplir prénom & noms
    matriculeInput.addEventListener('blur', () => {
      const matricule = matriculeInput.value.trim();
      if (matricule === "") {
        prenomInput.value = "";
        nomsInput.value = "";
        submitBtn.disabled = false;
        return;
      }

      fetch('?matricule=' + encodeURIComponent(matricule))
        .then(res => res.json())
        .then(data => {
          if (data.success) {
            prenomInput.value = data.prenom;
            nomsInput.value = data.noms;
            submitBtn.disabled = false;
          } else {
            prenomInput.value = "";
            nomsInput.value = "";
            submitBtn.disabled = true;
            Swal.fire({
              icon: 'error',
              title: 'Erreur',
              text: 'Étudiant introuvable.',
              confirmButtonColor: '#1a5276'
            });
          }
        });
    });

    // Validation JavaScript
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      const matricule = matriculeInput.value.trim();
      const mois = document.getElementById('mois').value.trim();
      const montant = document.getElementById('montant').value.trim();
      const date = document.getElementById('date_paiement').value;
      const mode = document.getElementById('mode_paiement').value;

      if (!matricule || !mois || !montant || !date || !mode) {
        Swal.fire({
          icon: 'warning',
          title: 'Champs manquants',
          text: 'Veuillez remplir tous les champs obligatoires.',
          confirmButtonColor: '#1a5276'
        });
        return;
      }

      form.submit();
    });

    // Redirection après enregistrement
    <?php if ($redirectId): ?>
    Swal.fire({
      icon: 'success',
      title: 'Paiement enregistré !',
      text: 'Vous allez être redirigé vers le reçu.',
      timer: 2500,
      showConfirmButton: false,
      background: '#ffffff',
      iconColor: '#27ae60'
    }).then(() => {
      window.location.href = 'recu_inscription.php?id=<?= $redirectId ?>';
    });
    <?php endif; ?>
  </script>
  
</body>
</html>