<?php
session_start();
include 'config/connexion.php';

// Gestion du logout AVANT tout affichage HTML
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['logout'])) {
    $client = null;
    $client_cin = '';
    // Optionnel : session_destroy(); // si vous voulez tout effacer
    header("Location: espace_client.php");
    exit;
}

// Authentification simple par CIN (à adapter selon vos besoins)
$client_cin = '';
$client = null;
$auth_error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['client_cin'])) {
    $client_cin = strtoupper(trim($_POST['client_cin']));
    $stmt = $conn->prepare("SELECT * FROM clients_table WHERE client_cin = ?");
    $stmt->bind_param("s", $client_cin);
    $stmt->execute();
    $result = $stmt->get_result();
    $client = $result->fetch_assoc();
    $stmt->close();
    if (!$client) {
        $auth_error = "CIN non trouvé.";
    }
}

// Si authentifié, charger les infos
$polices = [];
$paiements = [];
$solde = 0;
if ($client) {
    // Polices du client NON expirées
    $today = date('Y-m-d');
    $stmt = $conn->prepare("SELECT n_policy, immatriculation, end_date, policy_type FROM policy_table WHERE client_cin = ? AND end_date >= ?");
    $stmt->bind_param("ss", $client['client_cin'], $today);
    $stmt->execute();
    $res = $stmt->get_result();
    $polices = [];
    $polices_en_cours = [];
    while ($row = $res->fetch_assoc()) {
        $polices[] = $row;
        $polices_en_cours[] = $row['n_policy'];
    }
    $stmt->close();

    // Paiements du client pour les polices en cours uniquement
    $paiements = [];
    if (!empty($polices_en_cours)) {
        $in = implode(',', array_fill(0, count($polices_en_cours), '?'));
        $types = str_repeat('s', count($polices_en_cours) + 1); // +1 for client_cin
        $sql = "SELECT id, date_creation, montant_paye, paiement_statut, receipt_number, policy_number 
                FROM receipts_table 
                WHERE client_cin = ? AND policy_number IN ($in) 
                ORDER BY date_creation DESC";
        $stmt = $conn->prepare($sql);
        $params = array_merge([$client['client_cin']], $polices_en_cours);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $paiements[] = $row;
        }
        $stmt->close();
    }

    // Calcul du solde
    $sqlTotal = "SELECT SUM(montant_to_paie) as total_a_payer FROM policy_table WHERE client_cin = ?";
    $stmtTotal = $conn->prepare($sqlTotal);
    $stmtTotal->bind_param("s", $client['client_cin']);
    $stmtTotal->execute();
    $resTotal = $stmtTotal->get_result();
    $total_a_payer = 0;
    if ($resTotal && $rowTotal = $resTotal->fetch_assoc()) {
        $total_a_payer = floatval($rowTotal['total_a_payer']);
    }
    $stmtTotal->close();

    $sqlPaye = "SELECT SUM(montant_paye) as total_paye FROM receipts_table WHERE client_cin = ? AND paiement_statut = 1";
    $stmtPaye = $conn->prepare($sqlPaye);
    $stmtPaye->bind_param("s", $client['client_cin']);
    $stmtPaye->execute();
    $resPaye = $stmtPaye->get_result();
    $total_paye = 0;
    if ($resPaye && $rowPaye = $resPaye->fetch_assoc()) {
        $total_paye = floatval($rowPaye['total_paye']);
    }
    $stmtPaye->close();

    $solde = $total_paye - $total_a_payer;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <?php include('includes/head_code.php'); ?>
    <title>Espace Client</title>
    <style>
        .badge-solde { font-size: 1.1em; }
        .clickable-status { cursor:pointer; text-decoration:underline; }
    </style>
</head>
<body id="page-top">
<div id="wrapper">
    <div id="content-wrapper" class="d-flex flex-column">
        <div id="content">
            <div class="container-fluid" id="container-wrapper">
                <div class="d-sm-flex align-items-center justify-content-between mb-4">
                    <h1 class="h3 mb-0 text-gray-800">Espace Client</h1>
                </div>
                <?php if (!$client): ?>
                    <div class="row justify-content-center">
                        <div class="col-lg-6">
                            <div class="card mb-4">
                                <div class="card-header">Accès à votre espace</div>
                                <div class="card-body">
                                    <?php if ($auth_error): ?>
                                        <div class="alert alert-danger"><?php echo $auth_error; ?></div>
                                    <?php endif; ?>
                                    <form method="POST" action="">
                                        <div class="form-group">
                                            <label for="client_cin">Votre CIN</label>
                                            <input type="text" class="form-control" id="client_cin" name="client_cin" required>
                                        </div>
                                        <button type="submit" class="btn btn-primary">Accéder</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="row">
                        <div class="col-lg-6">
                            <div class="card mb-4">
                                <div class="card-header">Informations du client</div>
                                <div class="card-body">
                                    <ul class="list-group">
                                        <li class="list-group-item"><strong>CIN:</strong> <?php echo htmlspecialchars($client['client_cin']); ?></li>
                                        <li class="list-group-item"><strong>Nom:</strong> <?php echo htmlspecialchars($client['client_name']); ?></li>
                                        <li class="list-group-item"><strong>Entreprise:</strong> <?php echo htmlspecialchars($client['client_company']); ?></li>
                                    </ul>
                                    <div class="mt-3">
                                        <h5>Solde du client</h5>
                                        <?php if ($solde < 0): ?>
                                            <span class="badge badge-danger badge-solde">Débiteur : <?php echo number_format(abs($solde), 2, ',', ' '); ?> DH</span>
                                        <?php elseif ($solde > 0): ?>
                                            <span class="badge badge-success badge-solde">Créditeur : <?php echo number_format($solde, 2, ',', ' '); ?> DH</span>
                                        <?php else: ?>
                                            <span class="badge badge-secondary badge-solde">Solde nul</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="card mb-4">
                                <div class="card-header">Vos Polices (non expirées)</div>
                                <div class="card-body">
                                    <?php if (empty($polices)): ?>
                                        <div class="alert alert-info">Aucune police non expirée trouvée.</div>
                                    <?php else: ?>
                                        <table class="table table-bordered table-sm">
                                            <thead>
                                                <tr>
                                                    <th>Numéro</th>
                                                    <th>Type de police</th>
                                                    <th>Immatriculation</th>
                                                    <th>Date d'expiration</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                            <?php foreach ($polices as $p): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($p['n_policy']); ?></td>
                                                    <td><?php echo htmlspecialchars(isset($p['policy_type']) ? $p['policy_type'] : ''); ?></td>
                                                    <td>
                                                        <?php
                                                        $immat = trim($p['immatriculation']);
                                                        $immat_parts = preg_split('/\s*-\s*/u', $immat);
                                                        if (count($immat_parts) === 3) {
                                                            $part1 = trim($immat_parts[0]);
                                                            $part2 = trim($immat_parts[1]);
                                                            $part3 = trim($immat_parts[2]);
                                                            echo $part1 . ' - ' . '<span dir="rtl" style="display:inline-block;">' . $part2 . '</span>' . ' - ' . $part3;
                                                        } else {
                                                            echo htmlspecialchars($immat);
                                                        }
                                                        ?>
                                                    </td>
                                                    <td>
                                                        <?php
                                                            $date_exp = $p['end_date'];
                                                            echo $date_exp ? date('d/m/Y', strtotime($date_exp)) : '';
                                                        ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card mb-4">
                        <div class="card-header">Vos Paiements</div>
                        <div class="card-body">
                            <?php if (empty($paiements)): ?>
                                <div class="alert alert-info">Aucun paiement trouvé.</div>
                            <?php else: ?>
                                <table class="table table-bordered table-sm">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>N° police</th>
                                            <th>Montant (DH)</th>
                                            <th>Statut</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php foreach ($paiements as $pay): ?>
                                        <tr>
                                            <td>
                                                <?php
                                                    $date = $pay['date_creation'];
                                                    echo $date ? date('d/m/Y', strtotime($date)) : '';
                                                ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($pay['policy_number']); ?></td>
                                            <td><?php echo number_format($pay['montant_paye'], 2, ',', ' '); ?></td>
                                            <td>
                                                <span class="badge 
                                                    <?php
                                                        if ($pay['paiement_statut'] == 1) echo 'badge-success';
                                                        elseif ($pay['paiement_statut'] == 3) echo 'badge-danger';
                                                        else echo 'badge-warning';
                                                    ?>"
                                                    title="Afficher le reçu"
                                                >
                                                    <?php
                                                    if ($pay['paiement_statut'] == 1) {
                                                        echo 'Validé';
                                                    } elseif ($pay['paiement_statut'] == 3) {
                                                        echo 'Reffusé';
                                                    } else {
                                                        echo 'En cours';
                                                    }
                                                    ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                </table>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="text-center mb-4">
                        <form method="post" action="">
                            <button type="submit" name="logout" class="btn btn-danger">Quitter</button>
                        </form>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php include('includes/footer.php'); ?>
    </div>
</div>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="js/ruang-admin.min.js"></script>
</body>
</html>
