<?php
include 'config/connexion.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'
    ];
}
// 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_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_paye, $reste_a_payer, $agent, $paiement_mode, $paiement_ref, $echeance_date, $paiement_statut, $n_attestation);
$receipt = null;
if ($stmt->fetch()) {
    $receipt = array(
        'id' => $receipt_id,
        'receipt_number' => $receipt_number,
        'date_creation' => $date_creation,
        'policy_number' => $policy_number,
        'client_id' => $client_id,
        'client_name' => '',
        'immatriculation' => $immatriculation,
        'montant_paye' => $montant_paye,
        '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;
}

// Total payé pour cette police (depuis receipts_table)
$total_paid = 0;
$n_policy = $receipt['policy_number'];
$sql_total = "SELECT SUM(montant_paye) as total_paye FROM receipts_table WHERE policy_number = ?";
$stmt2 = $conn->prepare($sql_total);
$stmt2->bind_param("s", $n_policy);
$stmt2->execute();
$stmt2->bind_result($total_paye);
if ($stmt2->fetch()) {
    $total_paid = $total_paye ?? 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();

// Calculer la somme des paiements validés pour cette police
$total_paye_valide = 0;
$sql_valides = "SELECT SUM(montant_paye) as total_valides FROM receipts_table WHERE policy_number = ? AND paiement_statut = 1";
$stmt_valides = $conn->prepare($sql_valides);
$stmt_valides->bind_param("s", $n_policy);
$stmt_valides->execute();
$stmt_valides->bind_result($total_valides);
if ($stmt_valides->fetch()) {
    $total_paye_valide = floatval($total_valides ?? 0);
}
$stmt_valides->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 = '';
$chkCol = $conn->query("SHOW COLUMNS FROM policy_table LIKE 'next_paiement'");
$hasNext = ($chkCol && $chkCol->num_rows>0);
if($chkCol) $chkCol->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);
    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';
        $next_paiement = $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';
    }
}
$stmt_policy->close();

// Recalculer le reste à payer : montant total - somme des paiements validés
$reste_a_payer_calcule = $montant_to_paie - $total_paye_valide;
$receipt['reste_a_payer'] = $reste_a_payer_calcule;
?>
<!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;
        }
        .watermark {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%; /* Cover the entire page */
            transform: rotate(-45deg); /* Rotate the watermark diagonally */
            font-size: 200px;
            color: rgba(173, 216, 230, 0.5); /* Light blue with transparency */
            z-index: 1; /* Ensure it stays behind other elements */
            pointer-events: none;
            user-select: none;
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;
        }
        .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: right;
            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']) &&
                    in_array(strtoupper($receipt['paiement_mode']), ['CHEQUE', 'EFFET']) &&
                    !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>

        <!-- 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) pour la même attestation
                $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);
                $montant_total_paye = floatval($receipt['montant_paye']); // Paiement courant
                $has_history = false;
                while ($stmt_hist->fetch()) {
                    $has_history = true;
                    $row_hist = array(
                        'date_creation' => $hist_date_creation,
                        'receipt_number' => $hist_receipt_number,
                        'montant_paye' => $hist_montant_paye,
                        'agent' => $hist_agent,
                        'paiement_mode' => $hist_paiement_mode,
                        'paiement_statut' => $hist_paiement_statut
                    );
                    $montant_total_paye += floatval($row_hist['montant_paye']);
                    // Déterminer le texte du statut
                    $statut = '';
                    switch ($row_hist['paiement_statut']) {
                        case 3:
                            $statut = 'Reffusé';
                            break;
                        case 1:
                            $statut = 'Validé';
                            break;
                        default:
                            $statut = 'En cours';
                    }
                    echo '<tr>';
                    echo '<td>' . date('d/m/Y à H:i', strtotime($row_hist['date_creation'])) . '</td>';
                    echo '<td>' . htmlspecialchars($row_hist['receipt_number']) . '</td>';
                    // Montant line-through si refusé
                    if ($row_hist['paiement_statut'] == 3) {
                        echo '<td><span style="text-decoration: line-through;">' . number_format($row_hist['montant_paye'], 2, ',', ' ') . '</span></td>';
                    } else {
                        echo '<td>' . number_format($row_hist['montant_paye'], 2, ',', ' ') . '</td>';
                    }
                    // Mode de paiement line-through si refusé
                    if ($row_hist['paiement_statut'] == 3) {
                        echo '<td><span style="text-decoration: line-through;">' . htmlspecialchars($row_hist['paiement_mode']) . '</span></td>';
                    } else {
                        echo '<td>' . htmlspecialchars($row_hist['paiement_mode']) . '</td>';
                    }
                    echo '<td>' . $statut . '</td>';
                    echo '</tr>';
                }
                $stmt_hist->close();
                if (!$has_history) {
                    echo '<tr><td colspan="5" class="text-center text-muted">Aucun paiement précédent</td></tr>';
                }
                ?>
                </tbody>
            </table>
            <div class="total-section row mt-3">
                <div class="col-md-6">
                    <p>Agent: <?php echo htmlspecialchars($agent_name); ?></p>
                </div>
            </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>
        </div>
    </div>
    <div class="watermark">COPIE</div> <!-- Ensure this is outside the receipt-container -->
    <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>