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

// Vérifier que l'utilisateur est connecté
if (empty($_SESSION['user_email'])) {
    header('Location: login.php');
    exit;
}

// Traitement des actions (Appel passé / Reporter)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $numero_police_raw = $_POST['numero_police'] ?? '';
    $user_name = $_SESSION['user_name'] ?? 'Utilisateur';

    // Extraire une liste de numéros de polices (séparés par des virgules quand action sur "toutes les polices")
    $policies = array_filter(array_map('trim', explode(',', $numero_police_raw)));
    $policies = array_unique($policies);

    // Filtrer les formats suspects (garder alphanum + tiret/underscore seulement)
    $policies = array_values(array_filter($policies, function($p){ return preg_match('/^[A-Za-z0-9_-]+$/', $p); }));

    if ($action && !empty($policies)) {
        include 'includes/simple_log.php';
        try {
            // Récupérer les clients distincts liés aux polices sélectionnées
            $placeholdersClients = implode(',', array_fill(0, count($policies), '?'));
            $clientSql = "SELECT DISTINCT c.id, c.client_name FROM policy_table p LEFT JOIN clients_table c ON p.client_id = c.id WHERE p.n_policy IN ($placeholdersClients)";
            $stmtClient = $conn->prepare($clientSql);
            $typesClient = str_repeat('s', count($policies));
            $stmtClient->bind_param($typesClient, ...$policies);
            $stmtClient->execute();
            $stmtClient->bind_result($client_id_result, $client_name_result);
            $clientNames = [];
            while($stmtClient->fetch()) { $clientNames[] = $client_name_result ?: $client_id_result; }
            $stmtClient->close();
            $clientsDistinct = count($clientNames);
            $clientsLabel = $clientsDistinct . ' client' . ($clientsDistinct>1?'s':'');
            $clientsListStr = implode(', ', $clientNames);
            if ($action === 'appel_passe') {
                // Phased schedule: 30 -> 15 -> 7 -> 3 -> 1 jour(s) avant expiration, puis final.
                $todayDate = date('Y-m-d');
                $types = str_repeat('s', count($policies));
                $placeholders = implode(',', array_fill(0, count($policies), '?'));
                // Récupérer end_date par police
                $sel = $conn->prepare("SELECT n_policy, end_date FROM policy_table WHERE n_policy IN ($placeholders)");
                $sel->bind_param($types, ...$policies);
                $sel->execute();
                $sel->bind_result($n_policy_sel, $end_date_sel);
                $rows = [];
                while ($sel->fetch()) {
                    $rows[] = ['n_policy' => $n_policy_sel, 'end_date' => $end_date_sel];
                }
                $sel->close();
                $updatedNext = 0; $finalized = 0; $logDetails = [];
                foreach($rows as $row){
                    $npol = $row['n_policy'];
                    $endDate = $row['end_date'];
                    if(!$endDate) continue;
                    $daysLeft = (int)floor( (strtotime($endDate) - strtotime($todayDate)) / 86400 );
                    $newNext = null; $final = false;
                    if($daysLeft > 15){
                        // We are at first contact (30 days) -> schedule 15 days before
                        $target = strtotime($endDate . ' -15 days');
                        if($target >= strtotime($todayDate)) $newNext = date('Y-m-d', $target);
                    } elseif($daysLeft > 7){
                        $target = strtotime($endDate . ' -7 days');
                        if($target >= strtotime($todayDate)) $newNext = date('Y-m-d', $target);
                    } elseif($daysLeft > 3){
                        $target = strtotime($endDate . ' -3 days');
                        if($target >= strtotime($todayDate)) $newNext = date('Y-m-d', $target);
                    } elseif($daysLeft > 1){
                        $target = strtotime($endDate . ' -1 days');
                        if($target >= strtotime($todayDate)) $newNext = date('Y-m-d', $target);
                    } else {
                        // Final stage reached
                        $final = true;
                    }
                    if($final){
                        $upd = $conn->prepare("UPDATE policy_table SET appel = 1, next_call_date = NULL WHERE n_policy = ?");
                        $upd->bind_param('s', $npol);
                        $upd->execute();
                        $upd->close();
                        $finalized++;
                        $logDetails[] = "$npol:final";
                    } elseif($newNext){
                        $upd = $conn->prepare("UPDATE policy_table SET appel = 0, next_call_date = ? WHERE n_policy = ?");
                        $upd->bind_param('ss', $newNext, $npol);
                        $upd->execute();
                        $upd->close();
                        $updatedNext++;
                        $logDetails[] = "$npol->$newNext";
                    } else {
                        // No future phase (late call) -> finalize
                        $upd = $conn->prepare("UPDATE policy_table SET appel = 1, next_call_date = NULL WHERE n_policy = ?");
                        $upd->bind_param('s', $npol);
                        $upd->execute();
                        $upd->close();
                        $finalized++;
                        $logDetails[] = "$npol:finalLate";
                    }
                }
                // Notifications : marquer comme dismiss celles traitées maintenant
                $notifQuery = "UPDATE notifications SET is_dismissed = 1 WHERE type='appel_client' AND police_number IN ($placeholders)";
                $stmt_notif = $conn->prepare($notifQuery);
                $stmt_notif->bind_param($types, ...$policies);
                $stmt_notif->execute();
                $stmt_notif->close();
                logMessage("$user_name a passé appel (phases) pour $clientsLabel (".count($policies)." polices). Maj: next=$updatedNext final=$finalized Details=".implode('|',$logDetails));
                $_SESSION['success_message'] = "Appel traité: $updatedNext reprogrammé(s), $finalized finalisé(s) pour $clientsLabel.";
            } elseif ($action === 'reporter') {
                $next_call_date = date('Y-m-d', strtotime('+1 day'));
                $placeholders = implode(',', array_fill(0, count($policies), '?'));
                $query = "UPDATE policy_table SET appel = 0, next_call_date = ? WHERE n_policy IN ($placeholders)";
                $stmt = $conn->prepare($query);
                $types = 's' . str_repeat('s', count($policies));
                $params = array_merge([$next_call_date], $policies);
                $stmt->bind_param($types, ...$params);
                $stmt->execute();
                $affected = $stmt->affected_rows;
                $stmt->close();

                $notifQuery = "UPDATE notifications SET is_dismissed = 1 WHERE type='appel_client' AND police_number IN ($placeholders)";
                $stmt_notif = $conn->prepare($notifQuery);
                $stmt_notif->bind_param(str_repeat('s', count($policies)), ...$policies);
                $stmt_notif->execute();
                $stmt_notif->close();

                logMessage("$user_name a reporté l'appel de $clientsLabel (".count($policies)." police(s)) à demain ($next_call_date): ".implode(',', $policies));
                $_SESSION['success_message'] = "Appel reporté à demain ($next_call_date) pour $clientsLabel (".count($policies)." police(s)) : $clientsListStr. (Mises à jour: $affected)";
            } elseif ($action === 'reporter_custom') {
                $custom_date = $_POST['custom_date'] ?? '';
                $valid = false;
                if(preg_match('/^\d{4}-\d{2}-\d{2}$/', $custom_date)){
                    $ts = strtotime($custom_date);
                    if($ts!==false) $valid = true;
                }
                if(!$valid){
                    $_SESSION['error_message'] = "Date personnalisée invalide.";
                } else {
                    $placeholders = implode(',', array_fill(0, count($policies), '?'));
                    $query = "UPDATE policy_table SET appel = 0, next_call_date = ? WHERE n_policy IN ($placeholders)";
                    $stmt = $conn->prepare($query);
                    $types = 's' . str_repeat('s', count($policies));
                    $params = array_merge([$custom_date], $policies);
                    $stmt->bind_param($types, ...$params);
                    $stmt->execute();
                    $affected = $stmt->affected_rows;
                    $stmt->close();

                    $notifQuery = "UPDATE notifications SET is_dismissed = 1 WHERE type='appel_client' AND police_number IN ($placeholders)";
                    $stmt_notif = $conn->prepare($notifQuery);
                    $stmt_notif->bind_param(str_repeat('s', count($policies)), ...$policies);
                    $stmt_notif->execute();
                    $stmt_notif->close();

                    logMessage("$user_name a reporté l'appel de $clientsLabel (".count($policies)." police(s)) au $custom_date: ".implode(',', $policies));
                    $_SESSION['success_message'] = "Appel reporté au $custom_date pour $clientsLabel (".count($policies)." police(s)) : $clientsListStr. (Mises à jour: $affected)";
                }
            }
        } catch (Exception $e) {
            $_SESSION['error_message'] = "Erreur de mise à jour des appels: " . $e->getMessage();
        }
        header('Location: appels.php');
        exit;
    }
}

// Récupérer les polices expirant dans les 30 jours pour gérer les phases (30,15,7,3,1)
$today = date('Y-m-d');
$dateLimit30 = date('Y-m-d', strtotime('+30 days'));
$query = "SELECT p.n_policy, p.end_date, p.total_reste, p.immatriculation, p.client_id,
                                 p.montant_to_paie, p.montant_paye, p.policy_category, p.next_call_date,
                                 c.client_name, c.client_phone, c.client_company, c.client_cin
                    FROM policy_table p
                    LEFT JOIN clients_table c ON p.client_id = c.id
                    WHERE p.end_date BETWEEN CURDATE() AND ?
                    AND (p.appel IS NULL OR p.appel = 0)
                    AND (
                                p.next_call_date IS NULL
                                OR p.next_call_date <= CURDATE()
                            )
                    ORDER BY p.end_date ASC";

$stmt = $conn->prepare($query);
$stmt->bind_param("s", $dateLimit30);
$stmt->execute();
$stmt->bind_result($n_policy, $end_date, $total_reste, $immatriculation, $client_id, $montant_to_paie, $montant_paye, $policy_category, $next_call_date, $client_name, $client_phone, $client_company, $client_cin);
$policies = [];
while ($stmt->fetch()) {
    $policies[] = [
        'n_policy' => $n_policy,
        'end_date' => $end_date,
        'total_reste' => $total_reste,
        'immatriculation' => $immatriculation,
        'client_id' => $client_id,
        'montant_to_paie' => $montant_to_paie,
        'montant_paye' => $montant_paye,
        'policy_category' => $policy_category,
        'next_call_date' => $next_call_date,
        'client_name' => $client_name,
        'client_phone' => $client_phone,
        'client_company' => $client_company,
        'client_cin' => $client_cin
    ];
}
$stmt->close();

// Calcul du nombre de clients uniques concernés par au moins une police à appeler
$uniqueClients = [];
foreach ($policies as $p) {
    $client_id = $p['client_id'] ?? '';
    if ($client_id !== '') {
        $uniqueClients[$client_id] = true;
    }
}
$clientsCount = count($uniqueClients);

// Connection is managed globally; do not close it here.
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include('includes/head.php'); ?>
    <style>
        .notification-card {
            border-left: 5px solid #dc3545;
            transition: all 0.3s ease;
        }
        
        .notification-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }
        
        .notification-card.warning {
            border-left-color: #ffc107;
        }
        
        .notification-card.danger {
            border-left-color: #dc3545;
        }
        
        .notification-card.critical {
            border-left-color: #6f42c1;
            background: linear-gradient(145deg, #fff5f5 0%, #fee 100%);
        }
        
        .badge-days {
            font-size: 1rem;
            padding: 8px 12px;
            border-radius: 20px;
        }
        
        .action-buttons .btn {
            border-radius: 20px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            transition: all 0.3s ease;
        }
        
        .action-buttons .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        .btn-whatsapp {
            background:#25D366; border:none; color:#fff !important;
        }
        .btn-whatsapp:hover { background:#1ebe5d; color:#fff !important; }
    </style>
</head>

<body id="page-top">
    <div id="wrapper">
        <!-- Sidebar -->
        <?php include('includes/sidebar.php'); ?>
        <!-- Sidebar -->
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <!-- TopBar -->
                <?php include('includes/topbar.php'); ?>
                <!-- Topbar -->

                <!-- Container Fluid-->
                <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">
                            <i class="fas fa-phone text-primary mr-2"></i>
                            Appels Clients Pour Renouvellement de Police
                        </h1>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="dashboard.php">Accueil</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Appels Clients</li>
                        </ol>
                    </div>

                    <!-- Messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle mr-2"></i>
                            <?php echo htmlspecialchars($_SESSION['success_message']); ?>
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle mr-2"></i>
                            <?php echo htmlspecialchars($_SESSION['error_message']); ?>
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <!-- Statistiques -->
                    <div class="row mb-4">
                        <div class="col-lg-12">
                            <div class="card border-left-warning shadow">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                                Polices nécessitant une action
                                            </div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo $clientsCount; ?> Appels à effectuer
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-exclamation-triangle fa-2x text-warning"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Liste des polices -->
                    <div class="row">
                        <div class="col-lg-12">
                            <?php
                            if (empty($policies)) {
                                ?>
                                <div class="card shadow">
                                    <div class="card-body text-center py-5">
                                        <i class="fas fa-check-circle fa-3x text-success mb-3"></i>
                                        <h4 class="text-success">Aucun Appel pour le moment</h4>
                                        <p class="text-muted">Tous vos appels sont à jour !</p>
                                    </div>
                                </div>
                                <?php
                            } else {
                                // Regrouper les polices par client ID
                                $clients = [];
                                foreach ($policies as $policy) {
                                    $client_id = $policy['client_id'];
                                    if (!isset($clients[$client_id])) {
                                        $clients[$client_id] = [
                                            'client_name' => $policy['client_name'],
                                            'client_cin' => $policy['client_cin'],
                                            'client_phone' => $policy['client_phone'],
                                            'client_company' => $policy['client_company'],
                                            'policies' => []
                                        ];
                                    }
                                    $clients[$client_id]['policies'][] = $policy;
                                }
                                $todayDate = date('Y-m-d');
                                foreach ($clients as $client_id => $client) {
                                    // Filtrer les polices non expirées
                                    $filtered_policies = array_filter($client['policies'], function($policy) {
                                        return strtotime($policy['end_date']) >= strtotime(date('Y-m-d'));
                                    });
                                    if (empty($filtered_policies)) continue;
                                    // Calculer l'urgence max pour le client (la plus urgente de ses polices)
                                    $maxUrgency = 3; // warning
                                    $badgeClass = 'badge-info';
                                    $minDaysLeft = 999;
                                    foreach ($filtered_policies as $policy) {
                                        // Calcul normalisé des jours restants (différence de dates sans tenir compte de l'heure courante)
                                        $daysLeft = (int)floor( (strtotime($policy['end_date']) - strtotime($todayDate)) / 86400 );
                                        if ($daysLeft < $minDaysLeft) $minDaysLeft = $daysLeft;
                                        if ($daysLeft <= 1) {
                                            $maxUrgency = 1; $badgeClass = 'badge-danger';
                                        } elseif ($daysLeft <= 3 && $maxUrgency > 2) {
                                            $maxUrgency = 2; $badgeClass = 'badge-warning';
                                        }
                                    }
                                    $urgencyClass = ($maxUrgency === 1) ? 'critical' : (($maxUrgency === 2) ? 'danger' : 'warning');
                                    ?>
                                    <div class="card notification-card <?php echo $urgencyClass; ?> shadow mb-4">
                                        <div class="card-header py-3 d-flex justify-content-between align-items-center">
                                            <h6 class="m-0 font-weight-bold text-primary">
                                                <i class="fas fa-user text-primary mr-2"></i>
                                                <?php echo htmlspecialchars($client['client_name'] ?? 'N/A'); ?>
                                                <?php if (!empty($client['client_company'])): ?>
                                                    <small class="text-muted d-block">(<?php echo htmlspecialchars($client['client_company']); ?>)</small>
                                                <?php endif; ?>
                                            </h6>
                                            <span class="badge badge-days <?php echo $badgeClass; ?>">
                                                <?php
                                                $today = strtotime(date('Y-m-d'));
                                                if ($minDaysLeft === 0) {
                                                    echo '<i class="fas fa-exclamation-triangle mr-1"></i>Expire aujourd\'hui';
                                                } elseif ($minDaysLeft == 1) {
                                                    echo '<i class="fas fa-clock mr-1"></i>1 jour restant';
                                                } elseif ($minDaysLeft < 0) {
                                                    echo '<i class="fas fa-exclamation-triangle mr-1"></i>EXPIRÉE';
                                                } else {
                                                    echo '<i class="fas fa-calendar mr-1"></i>' . $minDaysLeft . ' jours restants';
                                                }
                                                ?>
                                            </span>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-8">
                                                    <p class="mb-2">
                                                        <strong><i class="fas fa-phone text-success mr-2"></i>Contact :</strong><br>
                                                        <?php
                                                            // Préparation numéro WhatsApp avec indicatif 212
                                                            $rawPhone = $client['client_phone'] ?? '';
                                                            $digitsPhone = preg_replace('/\D+/', '', $rawPhone);
                                                            $waNumber = '';
                                                            if($digitsPhone){
                                                                if(strpos($digitsPhone,'212')===0){
                                                                    $waNumber = $digitsPhone; // déjà avec indicatif
                                                                } else {
                                                                    if($digitsPhone[0]==='0') { $digitsPhone = substr($digitsPhone,1); }
                                                                    $waNumber = '212'.$digitsPhone;
                                                                }
                                                            }
                                                            // Trouver la police la plus proche (expiration la plus tôt)
                                                            $earliestPolicy = null;
                                                            foreach($filtered_policies as $pp){
                                                                if(!$earliestPolicy || strtotime($pp['end_date']) < strtotime($earliestPolicy['end_date'])){
                                                                    $earliestPolicy = $pp;
                                                                }
                                                            }
                                                            $waPolicyNum = $earliestPolicy['n_policy'] ?? '';
                                                            $waPolicyExp = $earliestPolicy ? date('d/m/Y', strtotime($earliestPolicy['end_date'])) : '';
                                                            // Récupérer nom agence (mis en cache dans variable statique pour ne pas répéter la requête)
                                                            static $AGENCE_NOM = null;
                                                            if($AGENCE_NOM === null){
                                                                $resAg = $conn->query("SELECT compagnie_name FROM compagnie_table LIMIT 1");
                                                                if($resAg && $rowAg = $resAg->fetch_assoc()){ $AGENCE_NOM = trim($rowAg['compagnie_name']); } else { $AGENCE_NOM=''; }
                                                            }
                                                            $signature = $AGENCE_NOM ? (' Merci. '.$AGENCE_NOM) : '';
                                                            $waMessage = 'Bonjour '.($client['client_name'] ?? '').', votre police N° '.$waPolicyNum.' va expirer le '.$waPolicyExp.'. Merci de passer avant cette date pour la renouveler.' . $signature;
                                                            $waUrl = $waNumber ? ('https://wa.me/'.$waNumber.'?text='.urlencode($waMessage)) : '';
                                                        ?>
                                                        <a href="tel:<?php echo htmlspecialchars($rawPhone); ?>"
                                                           class="text-decoration-none btn btn-success btn-sm font-weight-bold mr-2 mb-2"
                                                           style="font-size: 1.05rem; padding: 8px 15px;">
                                                            <i class="fas fa-phone mr-1"></i>
                                                            <?php echo htmlspecialchars($rawPhone ?: 'Non renseigné'); ?>
                                                        </a>
                                                        <?php if($waUrl): ?>
                                                        <a target="_blank" rel="noopener" href="<?php echo $waUrl; ?>" class="btn btn-whatsapp btn-sm font-weight-bold mb-2" style="font-size:1.05rem;padding:8px 14px;" title="Envoyer un WhatsApp">
                                                            <i class="fab fa-whatsapp mr-1"></i> WhatsApp
                                                        </a>
                                                        <?php endif; ?>
                                                    </p>
                                                    <div class="mb-2">
                                                        <strong>Polices à appeler :</strong>
                                                        <ul class="list-group mb-2">
                                                        <?php foreach ($filtered_policies as $policy): ?>
                                                            <li class="list-group-item">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                                                                                        <div>
                                                                                                                                                <?php
                                                                                                                                                      $expDateFmt = date('d/m/Y', strtotime($policy['end_date']));
                                                                                                                                                      $daysLeftPolicy = (int)floor( (strtotime($policy['end_date']) - strtotime($todayDate)) / 86400 );
                                                                                                                                                    $expBadgeClass = 'badge-success';
                                                                                                                                                    if($daysLeftPolicy <= 1) $expBadgeClass='badge-danger';
                                                                                                                                                    elseif($daysLeftPolicy <=3) $expBadgeClass='badge-warning';
                                                                                                                                                    elseif($daysLeftPolicy <=7) $expBadgeClass='badge-info';
                                                                                                                                                    elseif($daysLeftPolicy <=15) $expBadgeClass='badge-primary';
                                                                                                                                                    else $expBadgeClass='badge-secondary';
                                                                                                                                                ?>
                                                                                                                                                <span class="font-weight-bold">Police N° <?php echo htmlspecialchars($policy['n_policy']); ?></span>
                                                                                                                                                <span class="badge <?php echo $expBadgeClass; ?> ml-2" style="font-size:0.85rem;padding:6px 10px;" title="Expire dans <?php echo $daysLeftPolicy; ?> jour(s)" data-daysleft="<?php echo $daysLeftPolicy; ?>">
                                                                                                                                                    <i class="fas fa-hourglass-half mr-1"></i><?php echo $expDateFmt; ?>
                                                                                                                                                </span>
                                                                                                                                                <?php echo ($policy['policy_category'] === 'RD') ? '<span class="badge badge-warning ml-2">RD</span>' : '<span class="badge badge-info ml-2">V</span>'; ?>
                                                                                                                                                <br>
                                                                                                                                                <small>
                                                                            <strong>Type :</strong> <?php echo htmlspecialchars($policy['policy_category']); ?>
                                                                            <?php if (($policy['policy_category'] ?? 'V') === 'V') {
                                                                                $immat = trim($policy['immatriculation'] ?? '');
                                                                                if (!empty($immat)) {
                                                                                    $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 ' | <strong>Immatriculation :</strong> ' . $part3 . ' - <span dir="rtl" style="display:inline-block;">' . $part2 . '</span> - ' . $part1;
                                                                                    } else {
                                                                                        echo ' | <strong>Immatriculation :</strong> ' . htmlspecialchars($immat);
                                                                                    }
                                                                                } else {
                                                                                    echo ' | <strong>Immatriculation :</strong> N/A';
                                                                                }
                                                                            } else {
                                                                                echo ' | <strong>Immatriculation :</strong> ' . htmlspecialchars($policy['immatriculation']);
                                                                            }
                                                                            echo ' | <strong>Montant à payer :</strong> ' . number_format($policy['montant_to_paie'] ?? 0, 2, ',', ' ') . ' DH';
                                                                            echo ' | <strong>Payé :</strong> ' . number_format($policy['montant_paye'] ?? 0, 2, ',', ' ') . ' DH';
                                                                            echo ' | <strong>Reste :</strong> ' . number_format($policy['total_reste'] ?? 0, 2, ',', ' ') . ' DH';
                                                                        ?>
                                                                        </small>
                                                                    </div>
                                                                </div>
                                                            </li>
                                                        <?php endforeach; ?>
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="action-buttons">
                                                        <h6 class="font-weight-bold mb-3">Actions pour ce client :</h6>
                                                        <form method="POST" class="d-inline confirm-action" data-confirm-message="Confirmer : appel passé (toutes les polices) ?">
                                                            <input type="hidden" name="numero_police" value="<?php echo htmlspecialchars(implode(',', array_column($filtered_policies, 'n_policy'))); ?>">
                                                            <input type="hidden" name="action" value="appel_passe">
                                                            <button type="submit" class="btn btn-success btn-sm btn-block mb-2">
                                                                <i class="fas fa-phone mr-1"></i>
                                                                Appel Passé (toutes les polices)
                                                            </button>
                                                        </form>
                                                        <form method="POST" class="d-inline confirm-action" data-confirm-message="Confirmer : reporter à demain (toutes les polices) ?">
                                                            <input type="hidden" name="numero_police" value="<?php echo htmlspecialchars(implode(',', array_column($filtered_policies, 'n_policy'))); ?>">
                                                            <input type="hidden" name="action" value="reporter">
                                                            <button type="submit" class="btn btn-warning btn-sm btn-block">
                                                                <i class="fas fa-clock mr-1"></i>
                                                                Reporter à demain (toutes les polices)
                                                            </button>
                                                        </form><br>
                                                        <button type="button" class="btn btn-secondary btn-sm btn-block mb-2" onclick="toggleCustomDate('customDate_<?php echo $client_id; ?>')">
                                                            <i class="fas fa-calendar-plus mr-1"></i> Fixer une date
                                                        </button>
                                                        <form id="customDate_<?php echo $client_id; ?>" method="POST" class="border rounded p-2 mb-2 confirm-action" data-confirm-message="Confirmer : reprogrammer à cette date ?" style="display:none;background:#f9f6ff;" onsubmit="return this.custom_date.value ? true : (alert('Choisir une date'), false);">
                                                            <input type="hidden" name="numero_police" value="<?php echo htmlspecialchars(implode(',', array_column($filtered_policies, 'n_policy'))); ?>">
                                                            <input type="hidden" name="action" value="reporter_custom">
                                                            <label class="small font-weight-bold mb-1" style="color:#6f42c1;">Nouvelle date de rappel</label>
                                                            <div class="input-group input-group-sm mb-2">
                                                                <input type="date" name="custom_date" class="form-control" min="<?php echo date('Y-m-d'); ?>" value="" required>
                                                                <div class="input-group-append">
                                                                    <button class="btn btn-warning" type="submit" title="Valider"><i class="fas fa-check"></i></button>
                                                                    <button class="btn btn-outline-secondary" type="button" title="Annuler" onclick="toggleCustomDate('customDate_<?php echo $client_id; ?>')"><i class="fas fa-times"></i></button>
                                                                </div>
                                                            </div>
                                                            <small class="text-muted">Choisir une date future pour reprogrammer l'appel.</small>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php
                                }
                            }
                            ?>
                        </div>
                    </div>

                </div>
                <!---Container Fluid-->
            </div>
            <!-- Footer -->
            <?php include('includes/footer.php'); ?>
            <!-- Footer -->
        </div>
    </div>

    <!-- Scroll to top -->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <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>

    <script>
        $(document).ready(function() {
            // Animation des cartes au chargement
            $('.notification-card').each(function(index) {
                $(this).delay(index * 100).fadeIn(500);
            });
        });
                function toggleCustomDate(id){
                        var el=document.getElementById(id);
                        if(!el) return; el.style.display = (el.style.display==='none' || el.style.display==='') ? 'block':'none';
                }
                let pendingForm=null;
                document.addEventListener('DOMContentLoaded', function(){
                        document.querySelectorAll('form.confirm-action').forEach(f=>{
                                f.addEventListener('submit', function(e){
                                        if(f.dataset.confirmed==='1') return;
                                        e.preventDefault();
                                        pendingForm = f;
                                        const msg = f.getAttribute('data-confirm-message') || 'Confirmer cette action ?';
                                        document.getElementById('confirmModalMessage').textContent = msg;
                                        $('#confirmActionModal').modal('show');
                                });
                        });
                        document.getElementById('confirmModalValidate').addEventListener('click', function(){
                                if(pendingForm){ pendingForm.dataset.confirmed='1'; pendingForm.submit(); }
                        });
                });
    </script>

        <!-- Confirmation Modal -->
        <div class="modal fade" id="confirmActionModal" tabindex="-1" role="dialog" aria-labelledby="confirmActionModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header" style="background:#6f42c1;color:#fff;">
                        <h5 class="modal-title" id="confirmActionModalLabel"><i class="fas fa-question-circle mr-2"></i>Confirmation</h5>
                        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    </div>
                    <div class="modal-body"><p id="confirmModalMessage" class="mb-0">Confirmer cette action ?</p></div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
                        <button type="button" class="btn btn-primary" id="confirmModalValidate">Valider</button>
                    </div>
                </div>
            </div>
        </div>

</body>

</html>
