<?php
session_start();
require_once 'includes/dbconn.php';
require_once 'phpqrcode/qrlib.php';

function dateHeureLocaleSenegalFR() {
    setlocale(LC_TIME, 'fr_FR.UTF-8', 'fra');
    date_default_timezone_set('Africa/Dakar');
    $now = new DateTime('now');
    $formatted = strftime("%A %e %B %Y à %Hh%M", $now->getTimestamp());
    return ucfirst($formatted);
}

$id = intval($_GET['id'] ?? 0);
if ($id <= 0) { die("Reçu invalide."); }

$query = "SELECT m.id, m.montant, m.date_paiement, m.mois, m.mode_paiement, 
                 e.matricule, e.prenom, e.noms,
                 c.nom AS classe, n.nom_niveau AS niveau
          FROM mensualites m 
          JOIN etudiants e ON m.etudiant_id = e.id
          LEFT JOIN classes c ON e.classe_id = c.id
          LEFT JOIN niveaux n ON c.niveau_id = n.id
          WHERE m.id = $id LIMIT 1";
$result = mysqli_query($conn, $query);
if (!$result || mysqli_num_rows($result) === 0) {
    die("Reçu introuvable.");
}
$data = mysqli_fetch_assoc($result);

$qrText = "Ecole Sine Saloum Santé\nReçu N°: {$data['id']}\nMatricule: {$data['matricule']}\nNom: {$data['prenom']} {$data['noms']}\nClasse: {$data['classe']}\nMois: {$data['mois']}\nMontant: {$data['montant']} XOF\nDate: {$data['date_paiement']}\nMode: {$data['mode_paiement']}";
$filePath = sys_get_temp_dir() . '/qr_recu_' . $data['id'] . '.png';
QRcode::png($qrText, $filePath, QR_ECLEVEL_L, 3);
$qrBase64 = base64_encode(file_get_contents($filePath));
?>

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Reçu de Paiement - Ecole Sine Saloum Santé</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.0.0/css/all.min.css">
  <style>
    @page {
      size: A4 landscape;
      margin: 0;
    }
    @media print {
      body {
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
        background: white !important;
      }
      .no-print { display: none !important; }
      .page-break { page-break-after: always; }
    }
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      color: #333;
      background-color: #f5f5f5;
      margin: 0;
      padding: 0;
    }
    .receipt-container {
      width: 297mm;
      height: 210mm;
      margin: 0 auto;
      padding: 10mm;
      display: flex;
      justify-content: space-between;
    }
    .receipt {
      background: white;
      border-radius: 10px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.1);
      padding: 15px;
      width: 48%;
      border: 1px solid #e0e0e0;
      position: relative;
      overflow: hidden;
    }
    .receipt::before {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 5px;
      background: linear-gradient(90deg, #1a5276, #27ae60);
    }
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      border-bottom: 2px solid #1a5276;
      padding-bottom: 10px;
    }
    .school-info {
      flex: 1;
    }
    .school-name {
      font-size: 1.2rem;
      font-weight: 700;
      color: #1a5276;
      margin-bottom: 5px;
    }
    .school-details {
      font-size: 0.8rem;
      color: #2980b9;
    }
    .logo {
      max-height: 60px;
      filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.1));
    }
    .receipt-title {
      text-align: center;
      font-size: 1.5rem;
      font-weight: 700;
      color: #1a5276;
      margin: 10px 0;
      text-transform: uppercase;
      letter-spacing: 1px;
    }
    .receipt-number {
      text-align: right;
      font-weight: 600;
      color: #1a5276;
      margin-bottom: 10px;
      font-size: 0.9rem;
    }
    .student-info {
      margin-bottom: 15px;
    }
    .student-name {
      font-size: 1.1rem;
      font-weight: 600;
      margin-bottom: 5px;
      color: #1a5276;
    }
    .text-muted {
      font-size: 0.9rem;
      color: #6c757d;
    }
    .info-table {
      width: 100%;
      border-collapse: collapse;
      margin: 15px 0;
      font-size: 0.9rem;
    }
    .info-table th, .info-table td {
      padding: 8px 10px;
      border: 1px solid #e0e0e0;
      text-align: left;
    }
    .info-table th {
      background-color: #f1f8fe;
      font-weight: 600;
      color: #1a5276;
      width: 30%;
    }
    .amount {
      font-size: 1.1rem;
      font-weight: 700;
      color: #27ae60;
    }
    .footer {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      margin-top: 20px;
      padding-top: 15px;
      border-top: 2px dashed #1a5276;
    }
    .qr-code {
      width: 80px;
      height: 80px;
      border: 1px solid #e0e0e0;
      padding: 3px;
      background: white;
    }
    .signature {
      text-align: center;
    }
    .signature-line {
      width: 150px;
      border-top: 1px solid #1a5276;
      margin: 5px 0;
      display: inline-block;
    }
    .copy-label {
      font-style: italic;
      color: #6c757d;
      text-align: right;
      font-size: 0.8rem;
    }
    .print-btn {
      position: fixed;
      bottom: 20px;
      right: 20px;
      background: linear-gradient(to right, #1a5276, #2980b9);
      border: none;
      border-radius: 30px;
      padding: 10px 25px;
      color: white;
      font-weight: 600;
      box-shadow: 0 4px 6px rgba(0,0,0,0.1);
      z-index: 1000;
    }
    .back-btn {
      position: fixed;
      bottom: 20px;
      left: 20px;
      background: linear-gradient(to right, #6c757d, #95a5a6);
      border: none;
      border-radius: 30px;
      padding: 10px 25px;
      color: white;
      font-weight: 600;
      box-shadow: 0 4px 6px rgba(0,0,0,0.1);
      z-index: 1000;
    }
    .text-center.mt-3.text-muted.small {
      font-size: 0.8rem;
    }
  </style>
</head>
<body>

<div class="receipt-container">
  <!-- Premier exemplaire (Étudiant) -->
  <div class="receipt">
   <div class="header">
      <div class="school-info">
        <div class="school-name">CENTRE DE FORMATION MAIN IT-CENTER</div>
        <div class="school-details">
          Quartier Niary Tally| Tel: 76 947 21 10 </br> Email: mainitcenter@gmail.com
        </div>
      </div>
      <img src="assetss/logo.png" alt="Logo" class="logo">
    </div>

    <div class="receipt-title">
      REÇU DE PAIEMENT
    </div>

    <div class="receipt-number">
      N° Reçu: <?= str_pad($data['id'], 5, '0', STR_PAD_LEFT) ?> | Copie: Étudiant
    </div>

    <div class="student-info">
      <h4 class="student-name"><?= htmlspecialchars($data['prenom'] . ' ' . $data['noms']) ?></h4>
      <div class="text-muted">Matricule: <?= htmlspecialchars($data['matricule']) ?></div>
      <div class="text-muted">Classe: <?= htmlspecialchars($data['classe'] . ' (' . $data['niveau'] . ')') ?></div>
    </div>

    <table class="info-table">
      <tr>
        <th>Mois payé</th>
        <td><?= htmlspecialchars($data['mois']) ?></td>
      </tr>
      <tr>
        <th>Montant</th>
        <td class="amount"><?= number_format($data['montant'], 0, ',', ' ') ?> FCFA</td>
      </tr>
      <tr>
        <th>Date de paiement</th>
        <td><?= date('d/m/Y', strtotime($data['date_paiement'])) ?></td>
      </tr>
      <tr>
        <th>Mode de paiement</th>
        <td><?= htmlspecialchars($data['mode_paiement']) ?></td>
      </tr>
      <tr>
        <th>Date d'émission</th>
        <td><?= dateHeureLocaleSenegalFR() ?></td>
      </tr>
    </table>

    <div class="footer">
      <div class="qr-code">
        <img src="data:image/png;base64,<?= $qrBase64 ?>" alt="QR Code" width="80" height="80">
      </div>
      <div class="signature">
        <div class="mb-2">Le Caissier</div>
        <div class="signature-line"></div>
        <div class="copy-label">Signature et cachet</div>
      </div>
    </div>

    <div class="text-center mt-3 text-muted small">
      <i class="fas fa-info-circle me-1"></i>
      Ce reçu est valable comme justificatif de paiement. Merci de le conserver.
    </div>
  </div>

  <!-- Deuxième exemplaire (Administration) -->
  <div class="receipt">
    <div class="header">
      <div class="school-info">
        <div class="school-name">CENTRE DE FORMATION MAIN IT-CENTER</div>
        <div class="school-details">
          Quartier N76 947 21 10 | Email: mainitcenter@gmail.com
        </div>
      </div>
      <img src="assetss/logo.png" alt="Logo" class="logo">
    </div>

    <div class="receipt-title">
      REÇU DE PAIEMENT
    </div>

    <div class="receipt-number">
      N° Reçu: <?= str_pad($data['id'], 5, '0', STR_PAD_LEFT) ?> | Copie: Administration
    </div>

    <div class="student-info">
      <h4 class="student-name"><?= htmlspecialchars($data['prenom'] . ' ' . $data['noms']) ?></h4>
      <div class="text-muted">Matricule: <?= htmlspecialchars($data['matricule']) ?></div>
      <div class="text-muted">Classe: <?= htmlspecialchars($data['classe'] . ' (' . $data['niveau'] . ')') ?></div>
    </div>

    <table class="info-table">
      <tr>
        <th>Mois payé</th>
        <td><?= htmlspecialchars($data['mois']) ?></td>
      </tr>
      <tr>
        <th>Montant</th>
        <td class="amount"><?= number_format($data['montant'], 0, ',', ' ') ?> FCFA</td>
      </tr>
      <tr>
        <th>Date de paiement</th>
        <td><?= date('d/m/Y', strtotime($data['date_paiement'])) ?></td>
      </tr>
      <tr>
        <th>Mode de paiement</th>
        <td><?= htmlspecialchars($data['mode_paiement']) ?></td>
      </tr>
      <tr>
        <th>Date d'émission</th>
        <td><?= dateHeureLocaleSenegalFR() ?></td>
      </tr>
    </table>

    <div class="footer">
      <div class="qr-code">
        <img src="data:image/png;base64,<?= $qrBase64 ?>" alt="QR Code" width="80" height="80">
      </div>
      <div class="signature">
        <div class="mb-2">Le Caissier</div>
        <div class="signature-line"></div>
        <div class="copy-label">Signature et cachet</div>
      </div>
    </div>

    <div class="text-center mt-3 text-muted small">
      <i class="fas fa-info-circle me-1"></i>
      Ce reçu est valable comme justificatif de paiement. Merci de le conserver.
    </div>
  </div>
</div>

<button onclick="handlePrint()" class="print-btn no-print">
  <i class="fas fa-print me-2"></i>Imprimer le reçu
</button>

<a href="mensualites.php" class="back-btn no-print">
  <i class="fas fa-arrow-left me-2"></i>Retour
</a>

<script>
  function handlePrint() {
    const printBtn = document.querySelector('.print-btn');
    printBtn.disabled = true;
    printBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Impression...';
    
    const afterPrint = () => {
      setTimeout(() => {
        window.location.href = 'mensualite.php';
      }, 500);
    };
    
    if (window.matchMedia) {
      const mediaQueryList = window.matchMedia('print');
      mediaQueryList.addListener((mql) => {
        if (!mql.matches) {
          afterPrint();
        }
      });
    }
    
    window.onafterprint = afterPrint;
    
    window.print();
  }

  setTimeout(() => {
    const printBtn = document.querySelector('.print-btn');
    if (printBtn.disabled) {
      printBtn.disabled = false;
      printBtn.innerHTML = '<i class="fas fa-print me-2"></i>Imprimer le reçu';
    }
  }, 5000);
</script>

</body>
</html>