<?php
include 'config/connexion.php';
// Impression d'un reçu à partir de la base de données, style similaire à recu.php
// Récupérer les informations de la compagnie depuis la table compagnie_table
$sql_company = "SELECT compagnie_name, adresse, tel1, tel2, fax, whatsapp, mail_1, mail_2, mail_3, footer, logo, logo_format FROM compagnie_table LIMIT 1";
$result_company = $conn->query($sql_company);
$company_info = [];
if ($result_company && $row_company = $result_company->fetch_assoc()) {
    $company_info = [
        'name' => $row_company['compagnie_name'] ?? '',
        'address' => $row_company['adresse'] ?? '',
        'tel1' => $row_company['tel1'] ?? '',
        'tel2' => $row_company['tel2'] ?? '',
        'fax' => $row_company['fax'] ?? '',
        'whatsapp' => $row_company['whatsapp'] ?? '',
        'mail_1' => $row_company['mail_1'] ?? '',
        'mail_2' => $row_company['mail_2'] ?? '',
        'mail_3' => $row_company['mail_3'] ?? '',
        'footer' => $row_company['footer'] ?? '',
        'logo' => $row_company['logo'] ?? '',
        'logo_format' => $row_company['logo_format'] ?? 'wide'
    ];
} else {
    $company_info = [
        'name' => '', 'address' => '', 'tel1' => '', 'tel2' => '', 'fax' => '', 'whatsapp' => '', 'mail_1' => '', 'mail_2' => '', 'mail_3' => '', 'footer' => '', 'logo' => '', 'logo_format' => 'wide'
    ];
}
include 'config/connexion.php';

// Récupération du reçu et des paiements associés
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($id <= 0) {
    echo "<div style='text-align:center; margin-top:50px;'><h3>Erreur : Reçu introuvable.</h3><a href='liste_recus.php' class='btn btn-primary'>Retour</a></div>";
    exit;
}

// Charger le reçu
$sql = "SELECT id, receipt_number, date_creation, policy_number, client_id, immatriculation, montant_total, montant_paye, reste_a_payer, agent, paiement_mode, paiement_ref, echeance_date, paiement_statut, n_attestation FROM receipts_table WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($receipt_id, $receipt_number, $date_creation, $policy_number, $client_id, $immatriculation, $montant_total, $montant_paye_receipt, $reste_a_payer, $agent, $paiement_mode, $paiement_ref, $echeance_date, $paiement_statut, $n_attestation);
$receipt = null;
if ($stmt->fetch()) {
    $receipt = [
        'id' => $receipt_id,
        'receipt_number' => $receipt_number,
        'date_creation' => $date_creation,
        'policy_number' => $policy_number,
        'client_id' => $client_id,
        'client_name' => '',
        'immatriculation' => $immatriculation,
        'montant_total' => $montant_total,
        'montant_paye' => $montant_paye_receipt,
        'reste_a_payer' => $reste_a_payer,
        'agent' => $agent,
        'paiement_mode' => $paiement_mode,
        'paiement_ref' => $paiement_ref,
        'echeance_date' => $echeance_date,
        'paiement_statut' => $paiement_statut,
        'n_attestation' => $n_attestation
    ];
}
$stmt->close();

if (!$receipt) {
    echo "<div style='text-align:center; margin-top:50px;'><h3>Erreur : Reçu introuvable.</h3><a href='liste_recus.php' class='btn btn-primary'>Retour</a></div>";
    exit;
}

// Dernier paiement effectué pour cette police
$last_payment = null;
$total_paid = 0;
$n_policy = $receipt['policy_number'];
$sql_pay = "SELECT id, receipt_number, date_creation, policy_number, client_id, immatriculation, montant_total, montant_paye, reste_a_payer, agent, paiement_mode, paiement_ref, echeance_date, paiement_statut FROM receipts_table WHERE policy_number = ? ORDER BY id DESC LIMIT 1";
$stmt = $conn->prepare($sql_pay);
$stmt->bind_param("s", $n_policy);
$stmt->execute();
$stmt->bind_result($lp_id, $lp_receipt_number, $lp_date_creation, $lp_policy_number, $lp_client_id, $lp_immatriculation, $lp_montant_total, $lp_montant_paye, $lp_reste_a_payer, $lp_agent, $lp_paiement_mode, $lp_paiement_ref, $lp_echeance_date, $lp_paiement_statut);
if ($stmt->fetch()) {
    $last_payment = [
        'id' => $lp_id,
        'receipt_number' => $lp_receipt_number,
        'date_creation' => $lp_date_creation,
        'policy_number' => $lp_policy_number,
        'client_id' => $lp_client_id,
        'immatriculation' => $lp_immatriculation,
        'montant_total' => $lp_montant_total,
        'montant_paye' => $lp_montant_paye,
        'reste_a_payer' => $lp_reste_a_payer,
        'agent' => $lp_agent,
        'paiement_mode' => $lp_paiement_mode,
        'paiement_ref' => $lp_paiement_ref,
        'echeance_date' => $lp_echeance_date,
        'paiement_statut' => $lp_paiement_statut
    ];
}
$stmt->close();

// Total payé pour cette police (en tenant compte des paiements refusés)
$sql_total = "SELECT SUM(CASE WHEN paiement_statut != 2 THEN montant_paye ELSE 0 END) as total_paye, SUM(CASE WHEN paiement_statut = 2 THEN montant_paye ELSE 0 END) as montant_refuse FROM receipts_table WHERE policy_number = ?";
$stmt2 = $conn->prepare($sql_total);
$stmt2->bind_param("s", $n_policy);
$stmt2->execute();
$stmt2->bind_result($total_paye, $montant_refuse);
$montant_refuse = 0;
if ($stmt2->fetch()) {
    $total_paid = $total_paye ?? 0;
    $montant_refuse = $montant_refuse ?? 0;
}
$stmt2->close();

// Récupérer les informations du client depuis clients_table
$n_dossier = '';
$client_cin = '';
$client_phone = '';
$client_adresse = '';
$sql_client = "SELECT n_dossier, client_cin, client_phone, client_adresse, client_name FROM clients_table WHERE id = ?";
$stmt_client = $conn->prepare($sql_client);
$stmt_client->bind_param("i", $receipt['client_id']);
$stmt_client->execute();
$stmt_client->bind_result($n_dossier_result, $client_cin_result, $client_phone_result, $client_adresse_result, $client_name_result);
if ($stmt_client->fetch()) {
    $n_dossier = $n_dossier_result ?? '';
    $client_cin = $client_cin_result ?? '';
    $client_phone = $client_phone_result ?? '';
    $client_adresse = $client_adresse_result ?? '';
    // Mettre à jour le nom du client avec celui de la base de données
    if ($client_name_result) {
        $receipt['client_name'] = $client_name_result;
    }
}
$stmt_client->close();

// Récupérer le nom de l'agent depuis users_table
$agent_name = $receipt['agent'] ?? '';
if (is_numeric($receipt['agent'])) {
    $sql_agent = "SELECT first_name, last_name FROM users_table WHERE id = ?";
    $stmt_agent = $conn->prepare($sql_agent);
    $stmt_agent->bind_param("i", $receipt['agent']);
    $stmt_agent->execute();
    $stmt_agent->bind_result($agent_first_name, $agent_last_name);
    if ($stmt_agent->fetch()) {
        $agent_name = trim(($agent_first_name ?? '') . ' ' . ($agent_last_name ?? ''));
    }
    $stmt_agent->close();
}

// Calculer le montant total des paiements non validés pour cette police
$montant_non_valide = 0;
$sql_non_valide = "SELECT SUM(montant_paye) as total_non_valide FROM receipts_table WHERE policy_number = ? AND paiement_statut != 1 AND paiement_statut != 3";
$stmt_non_valide = $conn->prepare($sql_non_valide);
$stmt_non_valide->bind_param("s", $n_policy);
$stmt_non_valide->execute();
$stmt_non_valide->bind_result($total_non_valide);
if ($stmt_non_valide->fetch()) {
    $montant_non_valide = floatval($total_non_valide ?? 0);
}
$stmt_non_valide->close();

// Récupérer le montant total à payer, le reste à payer et le type de police depuis policy_table
$montant_to_paie = 0;
$total_reste = 0;
$policy_type = '';
$policy_category = 'V'; // Par défaut Véhicule
$next_paiement = '';
$colChk = $conn->query("SHOW COLUMNS FROM policy_table LIKE 'next_paiement'");
$hasNext = ($colChk && $colChk->num_rows>0);
if($colChk) $colChk->close();
$sql_policy = $hasNext ? "SELECT montant_to_paie, total_reste, policy_type, policy_category, next_paiement FROM policy_table WHERE n_policy = ?"
                       : "SELECT montant_to_paie, total_reste, policy_type, policy_category FROM policy_table WHERE n_policy = ?";
$stmt_policy = $conn->prepare($sql_policy);
$stmt_policy->bind_param("s", $n_policy);
$stmt_policy->execute();
if ($hasNext) {
    $stmt_policy->bind_result($montant_to_paie_result, $total_reste_result, $policy_type_result, $policy_category_result, $next_paiement_result);
} else {
    $stmt_policy->bind_result($montant_to_paie_result, $total_reste_result, $policy_type_result, $policy_category_result);
}
if ($stmt_policy->fetch()) {
    $montant_to_paie = floatval($montant_to_paie_result);
    $total_reste = floatval($total_reste_result);
    $policy_type = $policy_type_result ?? '';
    $policy_category = $policy_category_result ?? 'V';
    if($hasNext){ $next_paiement = $next_paiement_result ?? ''; }
}
$stmt_policy->close();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <?php include('includes/head.php'); ?>
      <style>
        body {
            font-family: 'Arial', sans-serif;
            line-height: 1.6;
            background-color: #f8f9fa;
            position: relative;
        }
        .receipt-container {
            margin: 20px auto;
            padding: 30px;
            background-color: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            border-radius: 5px;
            position: relative; /* Ensure the receipt container does not overlap the watermark */
            z-index: 1;
        }
        /* Remove the watermark styles */
        .watermark {
            display: none;
        }
        .receipt-header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #f0f0f0;
            padding-bottom: 15px;
        }
        .receipt-header h1 {
            color: #3a3a3a;
            font-size: 24px;
            margin-bottom: 5px;
        }
        .company-info {
            margin-bottom: 20px;
        }
        .receipt-details {
            margin-bottom: 30px;
        }
        .receipt-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .receipt-table th, .receipt-table td {
            padding: 10px;
            border: 1px solid #ddd;
        }
        .receipt-table th {
            background-color: #f5f5f5;
            text-align: left;
        }
        .total-section {
            border-top: 2px solid #f0f0f0;
            margin-top: 20px;
            padding-top: 15px;
            font-weight: bold;
        }
        .footer {
            margin-top: 50px;
            text-align: center;
            font-size: 12px;
            color: #777;
        }
        .signature-section {
            margin-top: 50px;
            display: flex;
            justify-content: space-between;
        }
        .signature-box {
            border-top: 1px solid #000;
            width: 200px;
            text-align: center;
            padding-top: 5px;
        }
        .qr-code {
            float: left;
            margin-top: -10px;
        }
        @media print {
            .no-print {
                display: none;
            }
            body {
                background-color: white;
            }
            .receipt-container {
                box-shadow: none;
                margin: 0;
                padding: 15px;
            }
        }
    </style>
</head>
<body>
    <div class="receipt-container">
        <div class="receipt-header">
            <div class="qr-code">
                <canvas id="qrcode"></canvas> <!-- QR code canvas -->
            </div>            <h1>Reçu de Paiement</h1>
            Date d'émission de reçu: <strong><?php echo date('d/m/Y à H:i', strtotime($receipt['date_creation'])); ?></strong><br>
            Numéro de reçu: <strong><?php echo htmlspecialchars($receipt['receipt_number']); ?></strong><br>
            Numéro de police: <strong><?php echo htmlspecialchars($receipt['policy_number']); ?></strong><br>
            <?php if (!empty($receipt['n_attestation'])): ?>
            Numéro d'attestation: <strong><?php echo htmlspecialchars($receipt['n_attestation']); ?></strong><br>
            <?php endif; ?>
            <?php if ($policy_category === 'RD'): ?>
                <i class="fas fa-shield-alt" style="color: #ffc107;"></i> Risque Divers : <strong><?php echo htmlspecialchars($policy_type); ?></strong><br>
            <?php else: ?>
                <i class="fas fa-car" style="color: #17a2b8;"></i>Assurance Véhicule : <strong><?php echo htmlspecialchars($policy_type); ?></strong><br>
            <?php endif; ?>
        </div>
        <div class="row">
            <div class="col-md-6 company-info">
                <h5><?php echo htmlspecialchars($company_info['name']); ?></h5>
                <p>
                  <?php echo htmlspecialchars($company_info['address']); ?><br>
                  <?php if (!empty($company_info['tel1'])): ?>Téléphone: <?php echo htmlspecialchars($company_info['tel1']); ?><br><?php endif; ?>
                  <?php if (!empty($company_info['mail_1'])): ?>Email: <?php echo htmlspecialchars($company_info['mail_1']); ?><br><?php endif; ?>
                </p>
            </div>
            <div class="col-md-6 company-info">
                <h5>CLIENT</h5>
                <p>                    <strong>Nom:</strong> <?php echo htmlspecialchars($receipt['client_name']); ?><br>
                    <strong>CIN:</strong> <?php echo htmlspecialchars($client_cin); ?><br>
                    <strong>Numéro de dossier:</strong> <?php echo htmlspecialchars($n_dossier); ?><br>
                    <!-- Affichage du numéro de dossier -->
                    <?php if ($policy_category === 'V'): ?>
                    <strong>Immatriculation:</strong> <span style="direction: ltr; unicode-bidi: bidi-override; display: inline-block;"><?php echo htmlspecialchars($receipt['immatriculation']); ?></span>
                    <?php endif; ?>
                </p>
            </div>
        </div>
        <div class="receipt-details">
            <h5>DÉTAILS DU PAIEMENT</h5>
            <table class="receipt-table">
                <tr>
                    <th>Montant payé</th>
                    <td><?php echo number_format($receipt['montant_paye'], 2, ',', ' '); ?> DH</td>
                </tr>
                <tr>
                    <th>Reste à payer</th>
                    <td><?php echo number_format($receipt['reste_a_payer'], 2, ',', ' '); ?> DH</td>
                </tr>
                <?php if ($montant_non_valide > 0): ?>
                <tr>
                    <th>Montant non validé</th>
                    <td style="color: #ffc107; font-weight: bold;"><?php echo number_format($montant_non_valide, 2, ',', ' '); ?> DH</td>
                </tr>
                <?php endif; ?>
                <tr>
                    <th>Mode de paiement</th>
                    <td><?php echo htmlspecialchars($receipt['paiement_mode'] ?? ''); ?></td>
                </tr>
                <?php if (
                    isset($receipt['paiement_mode']) &&
                    strtoupper($receipt['paiement_mode']) !== 'ESPECE' &&
                    !empty($receipt['paiement_ref'])
                ): ?>
                <tr>
                    <th>Numéro de chèque/Effet</th>
                    <td><?php echo htmlspecialchars($receipt['paiement_ref']); ?></td>
                </tr>
                <?php
                // Afficher la date d'échéance si disponible
                if (!empty($receipt['echeance_date'])): ?>
                <tr>
                    <th>Date d'échéance</th>
                    <td><?php echo htmlspecialchars(date('d/m/Y', strtotime($receipt['echeance_date']))); ?></td>
                </tr>
                <?php endif; ?>
                <?php endif; ?>
                <?php if(!empty($next_paiement)): ?>
                <tr>
                    <th>Prochain paiement prévu</th>
                    <td><?php echo htmlspecialchars(date('d/m/Y', strtotime($next_paiement))); ?></td>
                </tr>
                <?php endif; ?>
            </table>
        </div>

        <!-- Paiements non validés -->
        <?php
        // Récupérer les paiements non validés pour cette police
        $sql_non_valides = "SELECT receipt_number, date_creation, montant_paye, paiement_mode, paiement_ref, echeance_date FROM receipts_table WHERE policy_number = ? AND paiement_statut = 0 AND id != ? ORDER BY date_creation DESC";
        $stmt_nv = $conn->prepare($sql_non_valides);
        $stmt_nv->bind_param("si", $n_policy, $id);
        $stmt_nv->execute();
        $stmt_nv->bind_result($nv_receipt_number, $nv_date_creation, $nv_montant_paye, $nv_paiement_mode, $nv_paiement_ref, $nv_echeance_date);
        $paiements_non_valides = array();
        while ($stmt_nv->fetch()) {
            $paiements_non_valides[] = array(
                'receipt_number' => $nv_receipt_number,
                'date_creation' => $nv_date_creation,
                'montant_paye' => $nv_montant_paye,
                'paiement_mode' => $nv_paiement_mode,
                'paiement_ref' => $nv_paiement_ref,
                'echeance_date' => $nv_echeance_date
            );
        }
        $stmt_nv->close();
        ?>
        <?php if (!empty($paiements_non_valides)): ?>
        <div class="receipt-details">
            <h5>Paiements en attente de validation</h5>
            <table class="receipt-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>N° Reçu</th>
                        <th>Montant</th>
                        <th>Mode</th>
                        <th>N° Chèque/Effet</th>
                        <th>Échéance</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($paiements_non_valides as $pnv): ?>
                    <tr>
                        <td><?php echo htmlspecialchars(date('d/m/Y', strtotime($pnv['date_creation']))); ?></td>
                        <td><?php echo htmlspecialchars($pnv['receipt_number']); ?></td>
                        <td><?php echo number_format($pnv['montant_paye'], 2, ',', ' '); ?> DH</td>
                        <td><?php echo htmlspecialchars($pnv['paiement_mode']); ?></td>
                        <td><?php echo htmlspecialchars($pnv['paiement_ref'] ?? '-'); ?></td>
                        <td>
                            <?php 
                            if (!empty($pnv['echeance_date'])) {
                                echo htmlspecialchars(date('d/m/Y', strtotime($pnv['echeance_date'])));
                            } else {
                                echo '-';
                            }
                            ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>

        <!-- Historique des paiements précédents -->
        <div class="receipt-details">
            <h5>Historique des paiements précédents</h5>
            <table class="receipt-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Numéro de reçu</th>
                        <th>Montant (DH)</th>
                        <!-- <th>Agent</th> -->
                        <th>Mode de paiement</th>
                        <th>Statut de paiement</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                // Historique des paiements précédents (hors ce reçu)
                $sql_hist = "SELECT r.date_creation, r.receipt_number, r.montant_paye, r.agent, r.paiement_mode, r.paiement_statut FROM receipts_table r WHERE r.policy_number = ? AND r.n_attestation = ? AND r.id < ? ORDER BY r.date_creation DESC";
                $stmt_hist = $conn->prepare($sql_hist);
                $stmt_hist->bind_param("ssi", $n_policy, $receipt['n_attestation'], $id);
                $stmt_hist->execute();
                $stmt_hist->bind_result($hist_date_creation, $hist_receipt_number, $hist_montant_paye, $hist_agent, $hist_paiement_mode, $hist_paiement_statut);
                // Calcul du montant total payé (hors paiements refusés)
                $montant_total_paye = 0;
                $has_history = false;
                while ($stmt_hist->fetch()) {
                    $has_history = true;
                    // Déterminer le texte du statut
                    $statut = '';
                    switch ($hist_paiement_statut) {
                        case 3:
                            $statut = 'Reffusé';
                            break;
                        case 1:
                            $statut = 'Validé';
                            break;
                        default:
                            $statut = 'En cours';
                    }
                    // N'ajouter au total que si le paiement n'est pas refusé
                    if ($hist_paiement_statut != 3) {
                        $montant_total_paye += floatval($hist_montant_paye);
                    }
                    // Montant line-through si refusé
                    if ($hist_paiement_statut == 3) {
                        echo '<tr>';
                        echo '<td>' . date('d/m/Y à H:i', strtotime($hist_date_creation)) . '</td>';
                        echo '<td>' . htmlspecialchars($hist_receipt_number) . '</td>';
                        echo '<td><span style="text-decoration: line-through;">' . number_format($hist_montant_paye, 2, ',', ' ') . '</span></td>';
                        echo '<td><span style="text-decoration: line-through;">' . htmlspecialchars($hist_paiement_mode) . '</span></td>';
                        echo '<td>' . $statut . '</td>';
                        echo '</tr>';
                    } else {
                        echo '<tr>';
                        echo '<td>' . date('d/m/Y à H:i', strtotime($hist_date_creation)) . '</td>';
                        echo '<td>' . htmlspecialchars($hist_receipt_number) . '</td>';
                        echo '<td>' . number_format($hist_montant_paye, 2, ',', ' ') . '</td>';
                        echo '<td>' . htmlspecialchars($hist_paiement_mode) . '</td>';
                        echo '<td>' . $statut . '</td>';
                        echo '</tr>';
                    }
                }
                if (!$has_history) {
                    echo '<tr><td colspan="5" class="text-center text-muted">Aucun paiement précédent</td></tr>';
                }
                $stmt_hist->close();
                ?>
                </tbody>
            </table>
            <div class="total-section row mt-3">
                <div class="col-md-6">
                    <p>Agent: <?php echo htmlspecialchars($agent_name); ?></p>
                </div>
                <!-- Montant total payé supprimé -->
            </div>
        </div>
        <div class="signature-section">
            <div class="signature-box">
                <p>Signature de l'agent</p>
            </div>
        </div>
        <div class="footer">
            <p>Ce reçu est une preuve de paiement. Veuillez le conserver pour référence future.</p>
            <p>Pour toute question concernant cette police, veuillez contacter notre service client.</p>
        </div>
        
        <div class="no-print mt-4 text-center">
            <button onclick="window.print();" class="btn btn-primary">
                <i class="fas fa-print"></i> Imprimer le reçu
            </button>
            <a href="liste_recus.php" class="btn btn-secondary ml-2">
                Retour
            </a>
        </div>
    </div>
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/fontawesome-free/js/all.min.js"></script>
    <script>
        // Generate QR code with the link to the receipt
        const qr = new QRious({
            element: document.getElementById('qrcode'),
            value: window.location.href, // Use the current page URL
            size: 120 // Set the size of the QR code
        });
    </script>
</body>
</html>