<?php
ini_set('display_errors', 1);
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'
    ];
}

// Utiliser receipt_number passé en GET
$receipt_number = isset($_GET['receipt_number']) ? $_GET['receipt_number'] : '';

if ($receipt_number) {
    $sql = "SELECT r.receipt_number, r.policy_number, c.client_cin, c.client_name, r.immatriculation, r.montant_total, r.montant_paye, r.reste_a_payer, r.agent, r.date_creation, r.paiement_mode, r.paiement_ref, r.paiement_statut, r.echeance_date FROM receipts_table r LEFT JOIN clients_table c ON r.client_id = c.id WHERE r.receipt_number = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $receipt_number);
    $stmt->execute();
    $stmt->bind_result($receipt_number_result, $policy_number, $client_cin, $client_name, $immatriculation, $montant_total, $montant_paye, $reste_a_payer, $agent, $date_creation, $paiement_mode, $paiement_ref, $paiement_statut, $echeance_date);
    if ($stmt->fetch()) {
        // Fermer le statement principal avant d'en créer de nouveaux
        $stmt->close();
        
        // Récupérer le nom de l'agent à partir de son ID
        $agent_name = $agent; // Par défaut, utiliser l'ID comme nom
        if (is_numeric($agent)) {
            // Essayer différents noms de tables possibles pour les utilisateurs
            $user_tables = ['users_table', 'user_table', 'utilisateurs_table', 'agents_table'];
            
            foreach ($user_tables as $table) {
                // Essayer d'abord first_name et last_name
                $sql_agent = "SELECT first_name, last_name FROM $table WHERE id = ?";
                $stmt_agent = $conn->prepare($sql_agent);
                if ($stmt_agent) {
                    $stmt_agent->bind_param("i", $agent);
                    $stmt_agent->execute();
                    $stmt_agent->bind_result($first_name, $last_name);
                    if ($stmt_agent->fetch()) {
                        if (!empty($first_name) || !empty($last_name)) {
                            $agent_name = trim($first_name . ' ' . $last_name);
                            $stmt_agent->close();
                            break; // Sortir de la boucle
                        }
                    }
                    $stmt_agent->close();
                }
                
                // Si first_name/last_name ne marchent pas, essayer d'autres colonnes
                $user_name_columns = ['user_name', 'username', 'name', 'nom', 'agent_name'];
                foreach ($user_name_columns as $column) {
                    $sql_agent = "SELECT $column FROM $table WHERE id = ?";
                    $stmt_agent = $conn->prepare($sql_agent);
                    if ($stmt_agent) {
                        $stmt_agent->bind_param("i", $agent);
                        $stmt_agent->execute();
                        $stmt_agent->bind_result($user_name_result);
                        if ($stmt_agent->fetch() && !empty($user_name_result)) {
                            $agent_name = $user_name_result;
                            $stmt_agent->close();
                            break 2; // Sortir des deux boucles
                        }
                        $stmt_agent->close();
                    }
                }
            }
        }
        
        $receipt = array(
            'receipt_number' => $receipt_number_result,
            'policy_number' => $policy_number,
            'client_cin' => $client_cin,
            'client_name' => $client_name,
            'immatriculation' => $immatriculation,
            'montant_total' => $montant_total,
            'montant_paye' => $montant_paye,
            'reste_a_payer' => $reste_a_payer,
            'agent' => $agent_name,
            'date_creation' => $date_creation,
            'paiement_mode' => $paiement_mode,
            'paiement_ref' => $paiement_ref,
            'paiement_statut' => $paiement_statut,
            'echeance_date' => $echeance_date
        );
        $data = [
            'policy_id' => null,
            'client_cin' => $receipt['client_cin'],
            'client_name' => $receipt['client_name'],
            'immatriculation' => $receipt['immatriculation'],
            'n_policy' => $receipt['policy_number'],
            'start_date' => '',
            'end_date' => '',
            'montant_to_paie' => $receipt['montant_total'],
            'montant_paye' => $receipt['montant_paye'],
            'reste_a_payer' => $receipt['reste_a_payer'],
            'agent' => $receipt['agent'],
            'date_creation' => $receipt['date_creation'],
            'receipt_number' => $receipt['receipt_number']
        ];
        $paiement_mode = $receipt['paiement_mode'] ?? '';
        $paiement_ref = $receipt['paiement_ref'] ?? '';
    } else {
        $stmt->close();
        echo "<div style='text-align:center; margin-top:50px;'><h3>Erreur : Reçu introuvable.</h3><a href='new_policy.php' class='btn btn-primary'>Retour</a></div>";
        exit;
    }
} else {
    echo "<div style='text-align:center; margin-top:50px;'><h3>Erreur : Numéro de reçu manquant.</h3><a href='new_policy.php' class='btn btn-primary'>Retour</a></div>";
    exit;
}

// Calcul du débit (somme des total_reste pour ce client)
$debit = 0;
if (!empty($data['client_cin'])) {
    $sql_debit = "SELECT SUM(p.total_reste) AS debit_total FROM policy_table p LEFT JOIN clients_table c ON p.client_id = c.id WHERE c.client_cin = ?";
    $stmt_debit = $conn->prepare($sql_debit);
    $stmt_debit->bind_param("s", $data['client_cin']);
    $stmt_debit->execute();
    $stmt_debit->bind_result($debit_total);
    if ($stmt_debit->fetch()) {
        $debit = floatval($debit_total);
    }
    $stmt_debit->close();
}

// Vérifier si un reçu existe déjà pour cette police
$checkReceiptQuery = "SELECT id FROM receipts_table WHERE policy_number = ?";
$checkStmt = $conn->prepare($checkReceiptQuery);
$checkStmt->bind_param("s", $data['n_policy']);
$checkStmt->execute();
$checkStmt->bind_result($receipt_id_check);
$receiptExists = $checkStmt->fetch();
$checkStmt->close();

// Si aucun reçu n'existe pour cette police, on l'enregistre
if (!$receiptExists) {
    // Récupérer client_id à partir de client_cin
    $client_id = null;
    if (!empty($data['client_cin'])) {
        $sql_client = "SELECT id FROM clients_table WHERE client_cin = ?";
        $stmt_client = $conn->prepare($sql_client);
        $stmt_client->bind_param("s", $data['client_cin']);
        $stmt_client->execute();
        $stmt_client->bind_result($client_id);
        $stmt_client->fetch();
        $stmt_client->close();
    }
    
    // Insérer le reçu dans la base de données
    $insertQuery = "INSERT INTO receipts_table (
        receipt_number, 
        policy_number, 
        client_id, 
        immatriculation, 
        start_date, 
        end_date, 
        montant_total, 
        montant_paye, 
        reste_a_payer,
        agent,
        date_creation
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($insertQuery);
    $stmt->bind_param(
        "ssisssdddss",
        $receipt_number,
        $data['n_policy'],
        $client_id,
        $data['immatriculation'],
        $data['start_date'],
        $data['end_date'],
        $data['montant_to_paie'],
        $data['montant_paye'],
        $data['reste_a_payer'],
        $data['agent'],
        $data['date_creation']
    );
    
    // Exécuter la requête
    if (!$stmt->execute()) {
        $error = "Erreur lors de l'enregistrement du reçu: " . $stmt->error;
    }
    $stmt->close();
} else {
    // Récupérer le numéro de reçu existant
    $getReceiptQuery = "SELECT receipt_number FROM receipts_table WHERE policy_number = ?";
    $getStmt = $conn->prepare($getReceiptQuery);
    $getStmt->bind_param("s", $data['n_policy']);
    $getStmt->execute();
    $getStmt->bind_result($receipt_number_existing);
    if ($getStmt->fetch()) {
        $receipt_number = $receipt_number_existing;
    }
    $getStmt->close();
}

// Récupérer le numéro de dossier depuis clients_table
$n_dossier = '';
if (!empty($data['client_cin'])) {
    $sql_dossier = "SELECT n_dossier FROM clients_table WHERE client_cin = ?";
    $stmt_dossier = $conn->prepare($sql_dossier);
    $stmt_dossier->bind_param("s", $data['client_cin']);
    $stmt_dossier->execute();
    $stmt_dossier->bind_result($n_dossier_result);
    if ($stmt_dossier->fetch()) {
        $n_dossier = $n_dossier_result ?? '';
    }
    $stmt_dossier->close();
}

// Après récupération des infos de la police (policy_table), récupérer aussi le type de police + prochain paiement
$next_paiement = '';
$hasNextCol = false;
$chkCol = $conn->query("SHOW COLUMNS FROM policy_table LIKE 'next_paiement'");
if($chkCol && $chkCol->num_rows>0){ $hasNextCol = true; }
if($chkCol) $chkCol->close();
if($hasNextCol){
    $sql_policy = "SELECT montant_to_paie, policy_type, policy_category, next_paiement FROM policy_table WHERE n_policy = ?";
} else {
    $sql_policy = "SELECT montant_to_paie, policy_type, policy_category FROM policy_table WHERE n_policy = ?";
}
$stmt_policy = $conn->prepare($sql_policy);
$stmt_policy->bind_param("s", $data['n_policy']);
$stmt_policy->execute();
$montant_to_paie = 0;
$policy_type = '';
$policy_category = 'V'; // Par défaut Véhicule
if ($hasNextCol) {
    $stmt_policy->bind_result($montant_to_paie, $policy_type, $policy_category, $next_paiement);
} else {
    $stmt_policy->bind_result($montant_to_paie, $policy_type, $policy_category);
}
if ($stmt_policy->fetch()) {
        $montant_to_paie = floatval($montant_to_paie);
        $policy_type = $policy_type ?? '';
        $policy_category = $policy_category ?? 'V';
        if(!$hasNextCol){ $next_paiement = ''; }
}
$stmt_policy->close();

// Mettre à jour les données de session avec le numéro de reçu
$data['receipt_number'] = $receipt_number;
$_SESSION['receipt_data'] = $data;
?>
<!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 {
            max-width: 800px;
            margin: 20px auto;
            padding: 30px;
            background-color: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            border-radius: 5px;
            position: relative;
            z-index: 1;
        }
        .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: 30px;
        }
        @media print {
            .no-print {
                display: none;
            }
            body {
                background-color: white;
            }
            .receipt-container {
                box-shadow: none;
                margin: 0;
                padding: 15px;
            }
        }
    </style>
</head>
<body>
    <div class="">
        <div class="receipt-header">
            <div class="qr-code">
                <canvas id="qrcode"></canvas>
            </div>            <h1>REÇU DE PAIEMANT D'ASSURANCE</h1>
            Numéro de reçu: <strong><?php echo htmlspecialchars($receipt_number); ?></strong><br>
            Numéro de police: <strong><?php echo htmlspecialchars($data['n_policy']); ?></strong><br>
            Date d'émission: <strong><?php echo date('d/m/Y à H:i', strtotime($data['date_creation'])); ?></strong><br>
            <?php if ($policy_category === 'RD'): ?>
                <i class="fas fa-shield-alt text-warning mr-1"></i>Risque Divers : <strong><?php echo htmlspecialchars($policy_type); ?></strong>
            <?php else: ?>
                <i class="fas fa-car text-info mr-1"></i>Assurance Véhicule : <strong><?php echo htmlspecialchars($policy_type); ?></strong>
            <?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($data['client_name']); ?><br>                    <strong>CIN:</strong> <?php echo htmlspecialchars($data['client_cin']); ?><br>
                    <strong>Numéro de dossier:</strong> <?php echo htmlspecialchars($n_dossier); ?><br>
                    <?php if ($policy_category === 'V'): ?>
                    <strong>Immatriculation:</strong> <span style="unicode-bidi: bidi-override; direction: ltr; display: inline-block;"><?php echo htmlspecialchars($data['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($data['montant_paye'], 2, ',', ' '); ?> DH</td>
                </tr>
                <tr>
                    <th>Mode de paiement</th>
                    <td><?php echo htmlspecialchars($paiement_mode); ?></td>
                </tr>
                <?php if (
                    $paiement_mode &&
                    strtoupper($paiement_mode) !== 'ESPECE' &&
                    !empty($paiement_ref)
                ): ?>
                <tr>
                    <th>Numéro de chèque/Effet</th>
                    <td><?php echo htmlspecialchars($paiement_ref); ?></td>
                </tr>
                <?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>
        <div class="total-section row mt-3">
                <div class="col-md-6">
                    <p>Agent: <?php echo htmlspecialchars($receipt['agent']); ?></p>
                </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="policys_table.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>
        // Générer le QR code avec le lien du reçu
        new QRious({
            element: document.getElementById('qrcode'),
            value: window.location.href,
            size: 100
        });
    </script>
</body>
</html>