<?php
// Démarrer la session en premier
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Vérifier si l'utilisateur est connecté
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// Page imprimable : liste des paiements organisée par police et date
include 'config/connexion.php';

// Vérifier que la connexion est établie
if (!$conn) {
    die("Erreur de connexion à la base de données.");
}

$cin = isset($_GET['id']) ? trim($_GET['id']) : '';
$policy = isset($_GET['policy']) ? trim($_GET['policy']) : ''; // Récupération du paramètre 'policy'
$params = [];
$where = [];
if ($cin !== '') {
    $where[] = 'c.client_cin = ?';
    $params[] = $cin;
}
if ($policy !== '') {
    $where[] = 'r.policy_number = ?';
    $params[] = $policy;
}
$where_sql = '';
if (count($where) > 0) {
    $where_sql = 'WHERE ' . implode(' AND ', $where);
}
// Mise à jour de la requête SQL pour utiliser client_id et récupérer le nom de l'agent
$sql = "SELECT r.id, r.policy_number, r.immatriculation, r.agent, r.date_creation, r.montant_paye, r.reste_a_payer, r.receipt_number, r.n_attestation,
               c.client_cin, c.client_name, c.client_company, c.n_dossier, 
               p.montant_to_paie, p.montant_policy, p.policy_type, p.total_reste,
               CONCAT(u.first_name, ' ', u.last_name) as agent_name
        FROM receipts_table r
        LEFT JOIN clients_table c ON r.client_id = c.id
        LEFT JOIN policy_table p ON r.policy_number = p.n_policy
        LEFT JOIN users_table u ON r.agent = u.id
        $where_sql
        ORDER BY r.policy_number, r.date_creation ASC, r.id ASC";

// Utiliser une requête directe pour éviter les problèmes avec get_result()
if (count($params) === 1) {
    $safe_param = $conn->real_escape_string($params[0]);
    $sql_final = str_replace('?', "'" . $safe_param . "'", $sql);
} elseif (count($params) === 2) {
    $safe_param1 = $conn->real_escape_string($params[0]);
    $safe_param2 = $conn->real_escape_string($params[1]);
    $sql_final = $sql;
    $sql_final = preg_replace('/\?/', "'" . $safe_param1 . "'", $sql_final, 1);
    $sql_final = preg_replace('/\?/', "'" . $safe_param2 . "'", $sql_final, 1);
} else {
    $sql_final = $sql;
}
$res = $conn->query($sql_final);
// Organiser les paiements par police
$groupes = [];
if ($res && $res->num_rows > 0) {
    while ($row = $res->fetch_assoc()) {
    $key = $row['policy_number'];
    if (!isset($groupes[$key])) $groupes[$key] = [
        'immatriculation' => $row['immatriculation'],
        'client_name' => $row['client_name'],
        'client_cin' => $row['client_cin'],
        'client_company' => $row['client_company'],
        'policy_type' => $row['policy_type'],
        'montant_to_paie' => $row['montant_to_paie'],
        'montant_policy' => $row['montant_policy'],
        'total_reste' => $row['total_reste'],
        'paiements' => []
    ];
    $groupes[$key]['paiements'][] = [
        'id' => $row['id'],
        'date_creation' => $row['date_creation'],
        'montant_paye' => $row['montant_paye'],
        'reste_a_payer' => $row['reste_a_payer'],
        'agent' => $row['agent'],
        'agent_name' => $row['agent_name'],
        'receipt_number' => $row['receipt_number'],
        'n_dossier' => $row['n_dossier'],
        'n_attestation' => $row['n_attestation']
    ];
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <?php include ('includes/head.php'); ?>
    <style>
        body { background: #fff; font-family: Arial, sans-serif; }
        .container { max-width: 900px; margin: 30px auto; background: #fff; padding: 30px; box-shadow: 0 0 10px #eee; }
        h2 { margin-bottom: 30px; }
        .table th, .table td { vertical-align: middle; }
        .table thead th { background: #f5f5f5; }
        .police-section { margin-bottom: 40px; }
        @media print {
            .no-print { display: none; }
            .container { box-shadow: none; margin: 0; padding: 0; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 style="font-size:22px;"><?php echo $page_title ? htmlspecialchars($page_title) : 'HISTORIQUE DES PAIEMENTS'; ?></h2>
            <button onclick="window.print();" class="btn btn-primary no-print"><i class="fas fa-print"></i> Imprimer</button>
        </div>
        <?php if (empty($groupes)): ?>
            <div class="alert alert-info">Aucun paiement trouvé.</div>
        <?php else: ?>
            <?php foreach ($groupes as $policy => $infos): ?>
                <div class="police-section" style="page-break-inside: avoid;">
                    <div class="receipt-header" style="text-align:center; margin-bottom:20px; border-bottom:2px solid #f0f0f0; padding-bottom:10px;">
                        <div style="font-size:15px;">
                            
                        </div>
                        <div style="font-size:14px; margin-top:10px;">
                            <span>Date : <strong><?php echo date('d/m/Y H:i'); ?></strong></span>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-md-6">
                            <h5 style="color: #5e9ca0;"><strong style="text-decoration: underline;">CLIENT</strong></h5>
                            <p style="margin-bottom:0;">
                                <strong>Nom:</strong> <?php echo htmlspecialchars($infos['client_name']); ?><br>
                                <strong>CIN:</strong> <?php echo htmlspecialchars($infos['client_cin']); ?><br>
                            </p>
                        </div>
                        <div class="col-md-6">
                            <h5 style="color: #5e9ca0;"><strong style="text-decoration: underline;">POLICE</strong></h5>
                            <p style="margin-bottom:0;">
                                <strong>Numéro de police:</strong> <?php echo htmlspecialchars($policy); ?><br>
                                <strong>Montant de la police actuelle:</strong> <?php echo number_format($infos['montant_policy'] ?? 0, 2, ',', ' '); ?> DH<br>
                               
                            </p>
                        </div>
                    </div>
                    <hr>
                    <div class="receipt-details">
                        <h6 style="font-size:15px;">DÉTAILS DES PAIEMENTS</h6>
                        <table class="table table-bordered table-sm mt-2 receipt-table" style="font-size:14px;">
    <thead>
        <tr>
            <th>Date</th>
            <th>Numéro de reçu</th>
            <th>N° Attestation</th>
            <th>Montant</th>
            <th>Reste</th>
            <th>M.paiement</th>
            <th>Statut</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
    <?php 
    $total_paye_valide = 0; // Somme des paiements validés uniquement
    foreach ($infos['paiements'] as $p): 
        // Récupérer le mode de paiement et le statut depuis receipts_table
        $sql_mode_statut = "SELECT paiement_mode, paiement_statut FROM receipts_table WHERE id = ?";
        $stmt_mode_statut = $conn->prepare($sql_mode_statut);
        $stmt_mode_statut->bind_param("i", $p['id']);
        $stmt_mode_statut->execute();
        $stmt_mode_statut->bind_result($paiement_mode, $paiement_statut);
        $mode = '';
        $statut_val = 0;
        if ($stmt_mode_statut->fetch()) {
            $mode = $paiement_mode;
            $statut_val = intval($paiement_statut);
        }
        $stmt_mode_statut->close();

        // N'ajouter au total que si le paiement est validé
        if ($statut_val === 1) {
            $total_paye_valide += floatval($p['montant_paye']);
        }
    ?>
        <tr>
            <td><?php echo date('d/m/Y', strtotime($p['date_creation'])); ?></td>
            <td><?php echo htmlspecialchars($p['receipt_number']); ?></td>
            <td><?php echo !empty($p['n_attestation']) ? htmlspecialchars($p['n_attestation']) : '-'; ?></td>
            <td>
                <?php
                if ($statut_val === 3) {
                    echo '<span style="text-decoration: line-through;">' . number_format($p['montant_paye'], 2, ',', ' ') . ' DH</span>';
                } else {
                    echo number_format($p['montant_paye'], 2, ',', ' ') . ' DH';
                }
                ?>
            </td>
            <td>
                <?php
                if ($statut_val === 3) {
                    echo '<span style="text-decoration: line-through;">' . number_format($p['reste_a_payer'], 2, ',', ' ') . ' DH</span>';
                } else {
                    echo number_format($p['reste_a_payer'], 2, ',', ' ') . ' DH';
                }
                ?>
            </td>
            <td><?php echo htmlspecialchars($mode); ?></td>
            <td>
                <?php
                switch ($statut_val) {
                    case 1:
                        echo '<span class="text-success">Validé</span>';
                        break;
                    case 3:
                        echo '<span class="text-danger">Reffusé</span>';
                        break;
                    default:
                        echo '<span class="text-warning">En cours</span>';
                }
                ?>
            </td>
            <td><a href="print_receipt_copy.php?id=<?php echo intval($p['id']); ?>" class="btn btn-sm btn-info" title="Imprimer le reçu" target="_blank"><i class="fas fa-print"></i></a></td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
                    </div>
                    <div class="total-section" style="font-weight:bold; font-size:15px; border-top: 2px solid #5e9ca0; padding-top: 15px; margin-top: 15px;">
                        <div class="row">
                            <div class="col-md-6">
                            </div>
                            <div class="col-md-6 text-right">
                                <p style="margin-bottom: 5px;"><strong>Montant total à payer:</strong><span class="text-info"> <?php echo number_format($infos['montant_to_paie'] ?? 0, 2, ',', ' '); ?> DH</span> </p>
                                <p style="margin-bottom: 5px;"><strong>Reste à payer:</strong> <span class="text-danger"><?php echo number_format($infos['total_reste'] ?? 0, 2, ',', ' '); ?> DH</span></p>
                            </div>
                        </div>
                        <hr style="margin: 10px 0;">
                        <div style="font-size: 12px; color: #666; font-weight: normal; font-style: italic;">
                            <p style="margin-bottom: 3px;"><strong>Explications:</strong></p>
                            <p style="margin-bottom: 3px;">• <strong>Montant de la police actuelle</strong> = Le montant du dernier renouvellement</p>
                            <p style="margin-bottom: 3px;">• <strong>Montant total à payer</strong> = Montant de la police actuelle + reste impayé des périodes précédentes</p>
                            <p style="margin-bottom: 3px;">• <strong>Reste à payer</strong> = Montant total à payer - Total payé et validé</p>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    <link rel="stylesheet" href="vendor/fontawesome-free/css/all.min.css">
    <style>
        @media print {
            .police-section { page-break-after: always; }
            .no-print { display: none !important; }
            body { background: #fff !important; }
        }
    </style>
</body>
</html>
