<?php
// releve_compte.php
// Page de relevé de compte pour un client
include 'config/connexion.php';

$cin = isset($_GET['cin']) ? trim($_GET['cin']) : '';
$client = null;
$polices = [];
$paiements = [];
$solde = 0;
$error = '';

if ($cin === '') {
    $error = "Aucun CIN fourni.";
} else {
    // Récupérer le client
    $stmt = $conn->prepare("SELECT id, client_name FROM clients_table WHERE client_cin = ?");
    $stmt->bind_param("s", $cin);
    $stmt->execute();
    $stmt->bind_result($client_id, $client_name);
    if (!$stmt->fetch()) {
        $error = "Client introuvable.";
    } else {
        $client = array('id' => $client_id, 'client_name' => $client_name);
    }
    $stmt->close();
    
    if ($client) {
        // Récupérer les polices non totalement payées
        $sql = "SELECT n_policy, start_date, end_date, montant_to_paie, montant_paye, total_reste, policy_type, policy_category FROM policy_table WHERE client_id = ? AND total_reste > 0 ORDER BY end_date DESC";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $client['id']);
        $stmt->execute();
        $stmt->bind_result($n_policy, $start_date, $end_date, $montant_to_paie, $montant_paye, $total_reste, $policy_type, $policy_category);
        while ($stmt->fetch()) {
            $polices[] = array(
                'n_policy' => $n_policy,
                'start_date' => $start_date,
                'end_date' => $end_date,
                'montant_to_paie' => $montant_to_paie,
                'montant_paye' => $montant_paye,
                'total_reste' => $total_reste,
                'policy_type' => $policy_type,
                'policy_category' => $policy_category
            );
        }
        $stmt->close();
        // Récupérer les paiements
        $sql = "SELECT receipt_number, policy_number, montant_paye, paiement_mode, paiement_ref, paiement_statut, date_creation FROM receipts_table WHERE client_id = ? ORDER BY date_creation DESC";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $client['id']);
        $stmt->execute();
        $stmt->bind_result($receipt_number, $policy_number, $montant_paye, $paiement_mode, $paiement_ref, $paiement_statut, $date_creation);
        while ($stmt->fetch()) {
            // Mapping statut pour affichage
            $statutMap = [
                0 => ['label'=>'En attente','class'=>'warning'],
                1 => ['label'=>'Payé','class'=>'success'],
                2 => ['label'=>'Partiel','class'=>'info'],
                3 => ['label'=>'Annulé','class'=>'secondary'],
                4 => ['label'=>'Refusé','class'=>'danger']
            ];
            $code = isset($paiement_statut) ? (int)$paiement_statut : -1;
            $paiements[] = array(
                'receipt_number' => $receipt_number,
                'policy_number' => $policy_number,
                'montant_paye' => $montant_paye,
                'paiement_mode' => $paiement_mode,
                'paiement_ref' => $paiement_ref,
                'paiement_statut' => $paiement_statut,
                'date_creation' => $date_creation,
                'paiement_statut_label' => $statutMap[$code]['label'] ?? 'Inconnu',
                'paiement_statut_class' => $statutMap[$code]['class'] ?? 'dark'
            );
        }
        $stmt->close();
        // Calculer le solde du client (somme des total_reste sur toutes les polices)
        $sql = "SELECT SUM(total_reste) as solde FROM policy_table WHERE client_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $client['id']);
        $stmt->execute();
        $stmt->bind_result($solde_result);
        $solde = 0;
        if ($stmt->fetch()) {
            $solde = $solde_result ? number_format($solde_result, 2, '.', '') : '0.00';
        }
        $stmt->close();
    }
}
// Connection is managed globally; do not close it here.
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <?php include 'includes/head.php';?>
</head>
<body>
<div class="container mt-4">
    <h2>Relevé de compte client</h2>
    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php else: ?>
        <div class="card mb-3">
            <div class="card-body">
                <h5 class="card-title">Client : <?php echo htmlspecialchars($client['client_name']); ?> (<?php echo htmlspecialchars($cin); ?>)</h5>
                <p class="card-text"><strong>Solde restant à payer :</strong> <span class="text-danger"><?php echo $solde; ?> DH</span></p>
            </div>
        </div>
        <button class="btn btn-success mb-3" onclick="window.print()"><i class="fas fa-print"></i> Imprimer le relevé</button>
        <h4>Polices non totalement payées</h4>
        <table class="table table-bordered table-sm">
            <thead>
                <tr>
                    <th>N° Police</th>
                    <th>Type</th>
                    <th>Catégorie</th>
                    <th>Date début</th>
                    <th>Date fin</th>
                    <th>Montant à payer</th>
                    <th>Montant payé</th>
                    <th>Reste</th>
                </tr>
            </thead>
            <tbody>
            <?php if (count($polices) === 0): ?>
                <tr><td colspan="8" class="text-center">Aucune police en attente de paiement.</td></tr>
            <?php else: foreach ($polices as $p): ?>
                <tr>
                    <td><?php echo htmlspecialchars($p['n_policy']); ?></td>
                    <td><?php echo htmlspecialchars($p['policy_type']); ?></td>
                    <td><?php echo htmlspecialchars($p['policy_category']); ?></td>
                    <td><?php echo htmlspecialchars($p['start_date']); ?></td>
                    <td><?php echo htmlspecialchars($p['end_date']); ?></td>
                    <td><?php echo htmlspecialchars($p['montant_to_paie']); ?></td>
                    <td><?php echo htmlspecialchars($p['montant_paye']); ?></td>
                    <td class="text-danger"><?php echo htmlspecialchars($p['total_reste']); ?></td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
        <h4>Paiements effectués</h4>
        <table class="table table-bordered table-sm">
            <thead>
                <tr>
                    <th>N° Reçu</th>
                    <th>N° Police</th>
                    <th>Montant payé</th>
                    <th>Statut</th>
                    <th>Mode</th>
                    <th>Référence</th>
                    <th>Date</th>
                </tr>
            </thead>
            <tbody>
            <?php if (count($paiements) === 0): ?>
                <tr><td colspan="7" class="text-center">Aucun paiement trouvé.</td></tr>
            <?php else: foreach ($paiements as $pay): ?>
                <tr>
                    <td><?php echo htmlspecialchars($pay['receipt_number']); ?></td>
                    <td><?php echo htmlspecialchars($pay['policy_number']); ?></td>
                    <td><?php echo htmlspecialchars($pay['montant_paye']); ?></td>
                    <td><span class="badge badge-<?php echo htmlspecialchars($pay['paiement_statut_class']); ?>"><?php echo htmlspecialchars($pay['paiement_statut_label']); ?></span></td>
                    <td><?php echo htmlspecialchars($pay['paiement_mode']); ?></td>
                    <td><?php echo htmlspecialchars($pay['paiement_ref']); ?></td>
                    <td><?php echo htmlspecialchars($pay['date_creation']); ?></td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
    <?php endif; ?>
    <a href="clients_table.php" class="btn btn-secondary mt-3">Retour à la liste des clients</a>
</div>
</div>
<style>
@media print {
  body * { visibility: hidden; }
  .container, .container * { visibility: visible; }
  .container { position: absolute; left: 0; top: 0; width: 100vw; }
  @page { size: A4 landscape; margin: 10mm; }
  .btn, .btn-success, .btn-info, .btn-secondary { display: none !important; }
}
</style>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</div>
<script>
// Pagination des tableaux et numérotation des pages à l'impression
function addPageNumbers() {
  if (window.matchMedia('print').matches) return; // Ne rien faire hors impression
  let totalPages = Math.ceil(document.body.scrollHeight / window.innerHeight);
  let pageNumDiv = document.getElementById('page-numbers');
  if (!pageNumDiv) {
    pageNumDiv = document.createElement('div');
    pageNumDiv.id = 'page-numbers';
    pageNumDiv.style.position = 'fixed';
    pageNumDiv.style.bottom = '10mm';
    pageNumDiv.style.right = '20mm';
    pageNumDiv.style.fontSize = '14px';
    pageNumDiv.style.color = '#333';
    pageNumDiv.style.zIndex = '9999';
    document.body.appendChild(pageNumDiv);
  }
  pageNumDiv.innerHTML = 'Page 1/' + totalPages;
}
window.onbeforeprint = function() {
  // Ajoute le numéro de page à l'impression
  setTimeout(addPageNumbers, 100);
};
window.onafterprint = function() {
  let pageNumDiv = document.getElementById('page-numbers');
  if (pageNumDiv) pageNumDiv.remove();
};
</script>
</body>
</html>
