<?php
/**
 * Script automatique d'envoi de notifications d'expiration par email
 * Pour cron job - Aucune authentification requise
 * Envoie des emails bilingues (Français + Arabe)
 */

// Configuration pour éviter les timeouts
set_time_limit(300); // 5 minutes max
ini_set('memory_limit', '256M');

// Inclusion des fichiers nécessaires
include 'config/connexion.php';
include 'includes/email_functions.php';

// Configuration des échéances à surveiller (en jours)
$days_before_expiry = [30, 15, 7, 3, 1];

// Mode test si paramètre ?test=1 dans l'URL
$test_mode = isset($_GET['test']) && $_GET['test'] == '1';

// Mode automatique si paramètre ?auto=1 dans l'URL (pour cron)
$auto_mode = isset($_GET['auto']) && $_GET['auto'] == '1';

/**
 * Fonction pour obtenir les polices qui expirent bientôt
 */
function getPoliciesExpiringSoon($conn, $days) {
    $target_date = date('Y-m-d', strtotime("+$days days"));
    
    $sql = "SELECT p.*, c.client_email, c.client_name, c.client_cin,
                   DATEDIFF(p.end_date, CURDATE()) as days_until_expiry
            FROM policy_table p 
            LEFT JOIN clients_table c ON p.client_cin = c.client_cin
            WHERE DATE(p.end_date) = ?
              AND c.client_email IS NOT NULL 
              AND c.client_email != ''
              AND c.client_email != '0'
            ORDER BY p.end_date ASC";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $target_date);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $policies = [];
    while ($row = $result->fetch_assoc()) {
        $policies[] = $row;
    }
    $stmt->close();
    
    return $policies;
}

/**
 * Récupère les informations de la compagnie depuis la base de données
 */
function getCompanyInfo($conn) {
    $sql = "SELECT compagnie_name, adresse, tel1, tel2, whatsapp, footer 
            FROM compagnie_table 
            LIMIT 1";
    
    $result = $conn->query($sql);
    
    if ($result && $row = $result->fetch_assoc()) {
        return [
            'name' => $row['compagnie_name'] ?? 'HIBA ASSURANCE',
            'address' => $row['adresse'] ?? '',
            'tel1' => $row['tel1'] ?? '',
            'tel2' => $row['tel2'] ?? '',
            'whatsapp' => $row['whatsapp'] ?? '',
            'footer' => $row['footer'] ?? 'Intermédiaire d\'assurances régi par la loi 17-99.\nPortant code des assurances. Agrément n°C2653549002011450 du 29 Décembre 2010.\nRC: 44773 - IF: 40247708 - ICE: 000222791000001'
        ];
    }
    
    // Valeurs par défaut si la table n'existe pas ou est vide
    return [
        'name' => 'HIBA ASSURANCE',
        'address' => '',
        'tel1' => '',
        'tel2' => '',
        'whatsapp' => '',
        'footer' => 'Intermédiaire d\'assurances régi par la loi 17-99.\nPortant code des assurances. Agrément n°C2653549002011450 du 29 Décembre 2010.\nRC: 44773 - IF: 40247708 - ICE: 000222791000001'
    ];
}

/**
 * Génère le contenu HTML en français pour l'email
 */
function generateFrenchEmailContent($policy, $company_info) {
    $client_name = $policy['client_name'] ?? 'Client';
    $policy_number = $policy['n_policy'] ?? '';
    $end_date = date('d/m/Y', strtotime($policy['end_date']));
    $days_until_expiry = $policy['days_until_expiry'] ?? 0;
    
    // Texte adapté selon l'urgence
    if ($days_until_expiry <= 3) {
        $urgency_class = 'urgent';
        $urgency_icon = '🚨';
        $urgency_text = 'URGENT';
        $urgency_color = '#e53e3e';
    } elseif ($days_until_expiry <= 7) {
        $urgency_class = 'important';
        $urgency_icon = '⚠️';
        $urgency_text = 'IMPORTANT';
        $urgency_color = '#d69e2e';    } else {
        $urgency_class = 'normal';
        $urgency_icon = '📋';
        $urgency_text = 'RAPPEL';
        $urgency_color = '#3182ce';
    }
    
    // Préparer les informations de contact
    $contact_rows = '';
    if (!empty($company_info['tel1'])) {
        $contact_rows .= '<tr><td>📞 <strong></strong></td><td>' . htmlspecialchars($company_info['tel1']) . '</td></tr>';
    }
    if (!empty($company_info['tel2'])) {
        $contact_rows .= '<tr><td>📞 <strong></strong></td><td>' . htmlspecialchars($company_info['tel2']) . '</td></tr>';
    }
    if (!empty($company_info['whatsapp'])) {
        $contact_rows .= '<tr><td>💬 <strong></strong></td><td>' . htmlspecialchars($company_info['whatsapp']) . '</td></tr>';
    }
    if (!empty($company_info['address'])) {
        $contact_rows .= '<tr><td>📍 <strong></strong></td><td>' . htmlspecialchars($company_info['address']) . '</td></tr>';
    }
    
    // Si aucune information de contact, afficher le texte par défaut
    if (empty($contact_rows)) {
        $contact_rows = '
            <tr><td>📞 <strong>Téléphone :</strong></td><td>Contactez-nous par téléphone</td></tr>
            <tr><td>💬 <strong>WhatsApp :</strong></td><td>Contactez-nous sur WhatsApp</td></tr>
            <tr><td>📍 <strong>Visite :</strong></td><td>Rendez-vous à notre bureau</td></tr>';
    }
    
    // Préparer le footer
    $footer_lines = explode('\n', $company_info['footer']);
    $footer_html = '';
    foreach ($footer_lines as $index => $line) {
        $margin = $index === 0 ? 'margin:0;' : 'margin:5px 0 0;';
        $footer_html .= '<p style="' . $margin . '">' . htmlspecialchars($line) . '</p>';
    }    $html = '
    <!DOCTYPE html>
    <html lang="fr">
    <head>
        <meta charset="UTF-8">
        <title>Rappel d\'expiration - ' . htmlspecialchars($company_info['name']) . '</title>
    </head>
    <body style="margin:0; padding:0; font-family:\'Segoe UI\', sans-serif;">        <table width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td align="center">
                    <!-- Conteneur principal -->
                    <table width="600" cellpadding="0" cellspacing="0" style="background-color:#ffffff; margin-top:30px; border-radius:8px; overflow:hidden; box-shadow:0 4px 8px rgba(0,0,0,0.1); border:1px solid #e2e8f0;">

                        <!-- Header -->
                        <tr>
                            <td style="background-color:#4CAF50; padding:20px 30px; color:white; text-align:center;">
                                <h1 style="margin:0; font-size:24px;">🛡️ ' . htmlspecialchars($company_info['name']) . '</h1>
                                <p style="margin:0; font-size:14px;">Votre sécurité, notre priorité</p>
                            </td>
                        </tr>

                        <!-- Body -->
                        <tr>
                            <td style="padding:30px; color:#333;">
                                <h2 style="margin-top:0;">Bonjour ' . htmlspecialchars($client_name) . ',</h2>
                                <p>Nous vous informons que votre police d\'assurance arrive à expiration bientôt :</p>

                                <div style="background-color:#f9f9f9; padding:15px; border-left:5px solid #4CAF50; margin:20px 0;">
                                    <p><strong>Police :</strong> ' . htmlspecialchars($policy_number) . '</p>
                                    <p><strong>Date d\'expiration :</strong> ' . $end_date . '</p>
                                    <p><strong>Jours restants :</strong> <strong style="color:#e74c3c; font-size:18px;">' . $days_until_expiry . ' jour(s)</strong></p>
                                </div>

                                <p style="margin-bottom:20px;">Pour toute information complémentaire, vous pouvez nous contacter :</p>

                                <!-- Bloc de contact -->
                                <table style="width:100%; font-size:15px; line-height:1.6;">
                                    ' . $contact_rows . '
                                </table>

                            </td>
                        </tr>

                        <!-- Footer -->
                        <tr>
                            <td style="background-color:#f0f0f0; padding:20px 30px; text-align:center; font-size:12px; color:#777;">
                                <p style="margin:0;">' . htmlspecialchars($company_info['name']) . '</p>
                                ' . $footer_html . '
                            </td>
                        </tr>

                    </table>
                </td>
            </tr>
        </table>

    </body>
    </html>';
    
    return $html;
}

/**
 * Génère le contenu HTML en arabe pour l'email
 */
function generateArabicEmailContent($policy, $company_info) {
    $client_name = $policy['client_name'] ?? 'العميل الكريم';
    $policy_number = $policy['n_policy'] ?? '';
    $end_date = date('d/m/Y', strtotime($policy['end_date']));
    $days_until_expiry = $policy['days_until_expiry'] ?? 0;
    
    // Texte adapté selon l'urgence en arabe
    if ($days_until_expiry <= 3) {
        $urgency_class = 'urgent';
        $urgency_icon = '🚨';
        $urgency_text = 'عاجل جداً';
        $urgency_color = '#e53e3e';
    } elseif ($days_until_expiry <= 7) {
        $urgency_class = 'important';
        $urgency_icon = '⚠️';
        $urgency_text = 'مهم';
        $urgency_color = '#d69e2e';    } else {
        $urgency_class = 'normal';
        $urgency_icon = '📋';
        $urgency_text = 'تذكير';
        $urgency_color = '#3182ce';
    }
    
    // Préparer les informations de contact en arabe
    $contact_rows = '';
    if (!empty($company_info['tel1'])) {
        $contact_rows .= '<tr><td><strong>📞</strong></td><td>' . htmlspecialchars($company_info['tel1']) . '</td></tr>';
    }
    if (!empty($company_info['tel2'])) {
        $contact_rows .= '<tr><td><strong>📞</strong></td><td>' . htmlspecialchars($company_info['tel2']) . '</td></tr>';
    }
    if (!empty($company_info['whatsapp'])) {
        $contact_rows .= '<tr><td><strong>💬</strong></td><td>' . htmlspecialchars($company_info['whatsapp']) . '</td></tr>';
    }
    if (!empty($company_info['address'])) {
        $contact_rows .= '<tr><td><strong>📍</strong></td><td>' . htmlspecialchars($company_info['address']) . '</td></tr>';
    }
    
    // Si aucune information de contact, afficher le texte par défaut
    if (empty($contact_rows)) {
        $contact_rows = '
            <tr><td><strong>📞 :الهاتف</strong></td><td>اتصلوا بنا هاتفياً</td></tr>
            <tr><td><strong>💬 :واتساب</strong></td><td>اتصلوا بنا عبر الواتساب</td></tr>
            <tr><td><strong>📍 :الزيارة</strong></td><td>زوروا مكتبنا</td></tr>';
    }
    
    // Préparer le footer (garder en français comme demandé)
    $footer_lines = explode('\n', $company_info['footer']);
    $footer_html = '';
    foreach ($footer_lines as $index => $line) {
        $margin = $index === 0 ? 'margin:0;' : 'margin:5px 0 0;';
        $footer_html .= '<p style="' . $margin . '">' . htmlspecialchars($line) . '</p>';
    }    $html = '
    <!DOCTYPE html>
    <html dir="rtl" lang="ar">
    <head>
        <meta charset="UTF-8">
        <title>تذكير انتهاء الصلاحية - ' . htmlspecialchars($company_info['name']) . '</title>
    </head>
    <body style="margin:0; padding:0; font-family:\'Segoe UI\', sans-serif; direction:rtl;">        <table width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td align="center">
                    <!-- Conteneur principal -->
                    <table width="600" cellpadding="0" cellspacing="0" style="background-color:#ffffff; margin-top:30px; border-radius:8px; overflow:hidden; box-shadow:0 4px 8px rgba(0,0,0,0.1); border:1px solid #e2e8f0;">

                        <!-- Header -->
                        <tr>
                            <td style="background-color:#4CAF50; padding:20px 30px; color:white; text-align:center;">
                                <h1 style="margin:0; font-size:24px;">🛡️ ' . htmlspecialchars($company_info['name']) . '</h1>
                                <p style="margin:0; font-size:14px;">أمانكم أولويتنا</p>
                            </td>
                        </tr>

                        <!-- Body -->
                        <tr>
                            <td style="padding:30px; color:#333;">
                                <h2 style="margin-top:0;">مرحباً ' . htmlspecialchars($client_name) . '،</h2>
                                <p>نحيطكم علماً بأن بوليصة التأمين الخاصة بكم ستنتهي قريباً :</p>

                                <div style="background-color:#f9f9f9; padding:15px; border-right:5px solid #4CAF50; margin:20px 0;">
                                    <p><strong>البوليصة :</strong> ' . htmlspecialchars($policy_number) . '</p>
                                    <p><strong>تاريخ الانتهاء :</strong> ' . $end_date . '</p>
                                    <p><strong>الأيام المتبقية :</strong> <strong style="color:#e74c3c; font-size:18px;">' . $days_until_expiry . ' يوم/أيام</strong></p>
                                </div>

                                <p style="margin-bottom:20px;">لأي معلومات إضافية، يمكنكم التواصل معنا :</p>                                <!-- Bloc de contact -->
                                <table style="width:100%; font-size:15px; line-height:1.6; direction:rtl;">
                                    ' . $contact_rows . '
                                </table>

                            </td>
                        </tr>                        <!-- Footer -->
                        <tr>
                            <td style="background-color:#f0f0f0; padding:20px 30px; text-align:center; font-size:12px; color:#777;">
                                <p style="margin:0;">' . htmlspecialchars($company_info['name']) . '</p>
                                ' . $footer_html . '
                            </td>
                        </tr>

                    </table>
                </td>
            </tr>
        </table>

    </body>
    </html>';
    
    return $html;
}

/**
 * Log les notifications dans la base de données
 */
function logNotification($conn, $policy_id, $type, $recipient, $status, $details = '') {
    $sql = "INSERT INTO notification_log (policy_id, notification_type, recipient, status, sent_date, details) 
            VALUES (?, ?, ?, ?, NOW(), ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("issss", $policy_id, $type, $recipient, $status, $details);
    $stmt->execute();
    $stmt->close();
}

/**
 * Vérifie si une notification a déjà été envoyée aujourd'hui
 */
function hasNotificationSentToday($conn, $policy_id) {
    $sql = "SELECT id FROM notification_log 
            WHERE policy_id = ? 
              AND notification_type IN ('email_fr', 'email_ar') 
              AND DATE(sent_date) = CURDATE()
              AND status IN ('sent', 'simulated')";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $policy_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    return $result !== null;
}

// Variables pour le traitement
$results = [];
$total_sent = 0;
$total_failed = 0;
$total_skipped = 0;
$execution_start = microtime(true);

// Récupérer les informations de la compagnie
$company_info = getCompanyInfo($conn);

// Traitement automatique
foreach ($days_before_expiry as $days) {
    $policies = getPoliciesExpiringSoon($conn, $days);
    
    foreach ($policies as $policy) {
        $policy_id = $policy['id'];
        $client_email = $policy['client_email'];
        $client_name = $policy['client_name'];
        $policy_number = $policy['n_policy'];
        
        // Vérifier si notification déjà envoyée aujourd'hui
        if (!$test_mode && hasNotificationSentToday($conn, $policy_id)) {
            $total_skipped++;
            $results[] = [
                'policy' => $policy_number,
                'client' => $client_name,
                'email' => $client_email,
                'days' => $policy['days_until_expiry'],
                'status' => 'skipped',
                'message' => 'Notification déjà envoyée aujourd\'hui'
            ];
            continue;
        }
          // Préparer et envoyer l'email en français
        $subject_fr = "🛡️ Rappel d'expiration - Police $policy_number";
        $html_content_fr = generateFrenchEmailContent($policy, $company_info);
        
        // Préparer et envoyer l'email en arabe
        $subject_ar = "🛡️ تذكير انتهاء الصلاحية - بوليصة $policy_number";
        $html_content_ar = generateArabicEmailContent($policy, $company_info);
        
        $french_success = false;
        $arabic_success = false;
        $french_message = '';
        $arabic_message = '';
        
        // Envoyer l'email français ou simuler
        if ($test_mode) {
            // Mode test - simulation
            $french_result = [
                'success' => true,
                'message' => 'Email français simulé avec succès (mode test)'
            ];
            $french_success = true;
            $french_message = $french_result['message'];
        } else {
            // Envoi réel français
            $french_result = sendEmail($client_email, $subject_fr, $html_content_fr);
            $french_success = $french_result['success'];
            $french_message = $french_success ? 'Email français envoyé avec succès' : ($french_result['error'] ?? $french_result['message']);
        }
        
        // Logger le résultat français
        logNotification($conn, $policy_id, 'email_fr', $client_email, 
                       $test_mode ? 'simulated' : ($french_success ? 'sent' : 'failed'), 
                       $test_mode ? 'Mode test - Email français' : $french_message);
        
        // Délai entre les deux envois
        if (!$test_mode) {
            usleep(250000); // 0.25 seconde
        }
        
        // Envoyer l'email arabe ou simuler
        if ($test_mode) {
            // Mode test - simulation
            $arabic_result = [
                'success' => true,
                'message' => 'Email arabe simulé avec succès (mode test)'
            ];
            $arabic_success = true;
            $arabic_message = $arabic_result['message'];
        } else {
            // Envoi réel arabe
            $arabic_result = sendEmail($client_email, $subject_ar, $html_content_ar);
            $arabic_success = $arabic_result['success'];
            $arabic_message = $arabic_success ? 'Email arabe envoyé avec succès' : ($arabic_result['error'] ?? $arabic_result['message']);
        }
        
        // Logger le résultat arabe
        logNotification($conn, $policy_id, 'email_ar', $client_email, 
                       $test_mode ? 'simulated' : ($arabic_success ? 'sent' : 'failed'), 
                       $test_mode ? 'Mode test - Email arabe' : $arabic_message);
        
        // Compter les résultats combinés
        if ($french_success && $arabic_success) {
            $total_sent += 2; // 2 emails envoyés
            $results[] = [
                'policy' => $policy_number,
                'client' => $client_name,
                'email' => $client_email,
                'days' => $policy['days_until_expiry'],
                'status' => 'success',
                'message' => '✅ FR: ' . $french_message . ' | ✅ AR: ' . $arabic_message
            ];
        } elseif ($french_success || $arabic_success) {
            $total_sent += ($french_success ? 1 : 0) + ($arabic_success ? 1 : 0);
            $total_failed += (!$french_success ? 1 : 0) + (!$arabic_success ? 1 : 0);
            $results[] = [
                'policy' => $policy_number,
                'client' => $client_name,
                'email' => $client_email,
                'days' => $policy['days_until_expiry'],
                'status' => 'partial',
                'message' => ($french_success ? '✅' : '❌') . ' FR: ' . $french_message . ' | ' . 
                           ($arabic_success ? '✅' : '❌') . ' AR: ' . $arabic_message
            ];
        } else {
            $total_failed += 2; // 2 emails échoués
            $results[] = [
                'policy' => $policy_number,
                'client' => $client_name,
                'email' => $client_email,
                'days' => $policy['days_until_expiry'],
                'status' => 'error',
                'message' => '❌ FR: ' . $french_message . ' | ❌ AR: ' . $arabic_message
            ];
        }
        
        // Délai entre envois pour éviter la surcharge
        if (!$test_mode) {
            usleep(500000); // 0.5 seconde
        }
    }
}

$execution_time = round(microtime(true) - $execution_start, 2);

// En mode automatique (cron), afficher seulement les logs texte
if ($auto_mode) {
    echo "NOTIFICATIONS EXPIRATION - " . date('Y-m-d H:i:s') . "\n";
    echo "=========================================\n";
    echo "Mode: " . ($test_mode ? "TEST" : "PRODUCTION") . "\n";
    echo "Envoyés: $total_sent\n";
    echo "Échecs: $total_failed\n";
    echo "Ignorés: $total_skipped\n";
    echo "Durée: {$execution_time}s\n";
    echo "=========================================\n";
    
    foreach ($results as $result) {
        echo "[{$result['status']}] {$result['policy']} - {$result['client']} - {$result['message']}\n";
    }
    
    exit(0);
}

// Sinon, afficher l'interface HTML
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🤖 Notifications Automatiques - Cron Job</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        
        .header h1 {
            color: #4a5568;
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 700;
        }
        
        .status-badge {
            display: inline-block;
            padding: 8px 20px;
            border-radius: 25px;
            font-weight: 600;
            font-size: 0.9rem;
            margin: 5px;
            color: white;
        }
        
        .badge-success { background: #48bb78; }
        .badge-warning { background: #ed8936; }
        .badge-info { background: #4299e1; }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        
        .stat-number {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 10px;
        }
        
        .stat-label {
            color: #718096;
            font-size: 1rem;
            font-weight: 500;
        }
        
        .results-section {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        
        .result-item {
            background: #f7fafc;
            border-left: 4px solid #4299e1;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 8px;
        }
          .result-item.success { border-left-color: #48bb78; background: #f0fff4; }
        .result-item.error { border-left-color: #f56565; background: #fefefe; }
        .result-item.skipped { border-left-color: #ed8936; background: #fffbf0; }
        .result-item.partial { border-left-color: #f6ad55; background: #fefcbf; }
        
        .cron-info {
            background: rgba(255, 255, 255, 0.9);
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
            font-size: 0.9rem;
            color: #4a5568;
        }
        
        .url-examples {
            background: #2d3748;
            color: white;
            padding: 15px;
            border-radius: 8px;
            font-family: monospace;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>🤖 Notifications Automatiques</h1>
            <p style="color: #718096; font-size: 1.1rem; margin-bottom: 20px;">
                Système d'envoi de rappels d'expiration bilingues (Français + العربية)
            </p>
            
            <?php if ($test_mode): ?>
                <span class="status-badge badge-warning">🧪 Mode Test</span>
            <?php else: ?>
                <span class="status-badge badge-success">✅ Mode Production</span>
            <?php endif; ?>
            
            <span class="status-badge badge-info">📧 Email Uniquement</span>
            
            <div style="margin-top: 15px; font-size: 0.9rem; color: #718096;">
                Exécuté le <?php echo date('d/m/Y à H:i:s'); ?> - Durée: <?php echo $execution_time; ?>s
            </div>
        </div>

        <!-- Statistiques -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number" style="color: #48bb78;"><?php echo $total_sent; ?></div>
                <div class="stat-label">Envoyés</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #f56565;"><?php echo $total_failed; ?></div>
                <div class="stat-label">Échecs</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #ed8936;"><?php echo $total_skipped; ?></div>
                <div class="stat-label">Ignorés</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #4299e1;"><?php echo count($results); ?></div>
                <div class="stat-label">Total</div>
            </div>
        </div>

        <!-- Résultats -->
        <?php if (!empty($results)): ?>
        <div class="results-section">
            <h2 style="color: #4a5568; margin-bottom: 20px;">📧 Résultats d'envoi</h2>
            
            <?php foreach ($results as $result): ?>
            <div class="result-item <?php echo $result['status']; ?>">                <div style="font-weight: 600; margin-bottom: 5px;">
                    <?php if ($result['status'] === 'success'): ?>
                        ✅ Envoyés (FR + AR)
                    <?php elseif ($result['status'] === 'partial'): ?>
                        ⚠️ Partiel (FR/AR)
                    <?php elseif ($result['status'] === 'skipped'): ?>
                        ⏭️ Ignoré
                    <?php else: ?>
                        ❌ Échec (FR + AR)
                    <?php endif; ?>
                    - Police <?php echo htmlspecialchars($result['policy']); ?>
                    <span style="float: right; background: #e2e8f0; padding: 3px 8px; border-radius: 10px; font-size: 0.8rem;">
                        <?php echo $result['days']; ?> jour<?php echo $result['days'] > 1 ? 's' : ''; ?>
                    </span>
                </div>
                <div style="font-size: 0.9rem; color: #718096;">
                    👤 <?php echo htmlspecialchars($result['client']); ?><br>
                    📧 <?php echo htmlspecialchars($result['email']); ?><br>
                    💬 <?php echo htmlspecialchars($result['message']); ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="results-section">
            <div style="text-align: center; color: #718096; padding: 40px;">
                🔍 Aucune notification à envoyer aujourd'hui
            </div>
        </div>
        <?php endif; ?>

        <!-- Informations Cron -->
        <div class="cron-info">
            <h3 style="color: #2d3748; margin-bottom: 15px;">⚙️ Configuration pour Cron Job</h3>
            
            <p><strong>URLs d'accès :</strong></p>
            
            <div class="url-examples">
# Mode production (envoi réel)
curl "http://votre-domaine.com/hiba/notifications_cron.php?auto=1"

# Mode test (simulation)
curl "http://votre-domaine.com/hiba/notifications_cron.php?auto=1&test=1"

# Interface web
http://votre-domaine.com/hiba/notifications_cron.php
            </div>
            
            <p><strong>Exemple de crontab (exécution quotidienne à 9h00) :</strong></p>
            <div class="url-examples">
0 9 * * * curl -s "http://votre-domaine.com/hiba/notifications_cron.php?auto=1" >> /var/log/notifications.log 2>&1
            </div>
              <p style="margin-top: 15px;">
                <strong>📋 Échéances surveillées :</strong> 30, 15, 7, 3, et 1 jour avant expiration<br>
                <strong>🌐 Format :</strong> 2 emails séparés par client (Français + Arabe)<br>
                <strong>🔄 Anti-doublon :</strong> Maximum 1 série d'envois par jour par police
            </p>
        </div>
    </div>
</body>
</html>
