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

// 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';

// Configuration BulkSMS.ma
$BULKSMS_CONFIG = [
    'username' => 'votre_username', // À configurer
    'password' => 'votre_password', // À configurer
    'api_url' => 'https://www.bulksms.ma/developer/api/v1/send'
];

// 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_phone, 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_phone IS NOT NULL 
              AND c.client_phone != ''
              AND c.client_phone != '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, tel1, whatsapp 
            FROM compagnie_table 
            LIMIT 1";
    
    $result = $conn->query($sql);
    
    if ($result && $row = $result->fetch_assoc()) {
        return [
            'name' => $row['compagnie_name'] ?? 'HIBA ASSURANCE',
            'tel1' => $row['tel1'] ?? '',
            'whatsapp' => $row['whatsapp'] ?? ''
        ];
    }
    
    // Valeurs par défaut si la table n'existe pas ou est vide
    return [
        'name' => 'HIBA ASSURANCE',
        'tel1' => '',
        'whatsapp' => ''
    ];
}

/**
 * Génère le message SMS bilingue (FR + AR)
 */
function generateBilingueSMSContent($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;
    $company_name = $company_info['name'];
    
    // Message en français
    $message_fr = "Bonjour {$client_name}, votre assurance N°{$policy_number} va expirer le {$end_date}. Veuillez passer chez nous pour la renouveler. Cordialement {$company_name}.";
    
    // Message en arabe
    $message_ar = "مرحباً {$client_name}، تأمينكم رقم {$policy_number} سينتهي في {$end_date}. يرجى زيارتنا لتجديده. مع التحية {$company_name}.";
    
    // Combiner les deux messages avec séparateur
    $message = $message_fr . "\n---\n" . $message_ar;
    
    return $message;
}

/**
 * Normalise le numéro de téléphone au format international
 */
function normalizePhoneNumber($phone) {
    // Supprimer tous les caractères non numériques sauf le +
    $phone = preg_replace('/[^\d+]/', '', $phone);
    
    // Si le numéro commence par 0, remplacer par +212
    if (substr($phone, 0, 1) === '0') {
        $phone = '+212' . substr($phone, 1);
    }
    
    // Si le numéro ne commence pas par +, ajouter +212
    if (substr($phone, 0, 1) !== '+') {
        $phone = '+212' . $phone;
    }
    
    return $phone;
}

/**
 * Envoie un SMS via BulkSMS.ma
 */
function sendSMS($phone, $message, $config) {
    $phone = normalizePhoneNumber($phone);
    
    $data = [
        'username' => $config['username'],
        'password' => $config['password'],
        'msisdn' => $phone,
        'sid' => 'HIBA_ASSUR', // Sender ID (max 11 caractères)
        'msg' => $message,
        'fl' => '0' // Flash SMS (0 = non, 1 = oui)
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $config['api_url']);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded'
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_error) {
        return [
            'success' => false,
            'error' => 'Erreur CURL: ' . $curl_error
        ];
    }
    
    if ($http_code !== 200) {
        return [
            'success' => false,
            'error' => 'HTTP ' . $http_code . ': ' . $response
        ];
    }
    
    // Analyser la réponse de BulkSMS.ma
    $response_data = json_decode($response, true);
    
    if ($response_data && isset($response_data['status'])) {
        if ($response_data['status'] === 'success') {
            return [
                'success' => true,
                'message' => 'SMS envoyé avec succès',
                'sms_id' => $response_data['sms_id'] ?? null
            ];
        } else {
            return [
                'success' => false,
                'error' => $response_data['message'] ?? 'Erreur inconnue'
            ];
        }
    }
    
    return [
        'success' => false,
        'error' => 'Réponse invalide du serveur: ' . $response
    ];
}

/**
 * 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 SMS a déjà été envoyée aujourd'hui
 */
function hasSMSNotificationSentToday($conn, $policy_id) {
    $sql = "SELECT id FROM notification_log 
            WHERE policy_id = ? 
              AND notification_type = 'sms_bilingue' 
              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_phone = $policy['client_phone'];
        $client_name = $policy['client_name'];
        $policy_number = $policy['n_policy'];
        
        // Vérifier si notification SMS déjà envoyée aujourd'hui
        if (!$test_mode && hasSMSNotificationSentToday($conn, $policy_id)) {
            $total_skipped++;
            $results[] = [
                'policy' => $policy_number,
                'client' => $client_name,
                'phone' => $client_phone,
                'days' => $policy['days_until_expiry'],
                'status' => 'skipped',
                'message' => 'SMS déjà envoyé aujourd\'hui'
            ];
            continue;
        }
        
        // Préparer le message SMS bilingue
        $sms_content = generateBilingueSMSContent($policy, $company_info);
        
        $sms_success = false;
        $sms_message = '';
        
        // Envoyer le SMS ou simuler
        if ($test_mode) {
            // Mode test - simulation
            $sms_result = [
                'success' => true,
                'message' => 'SMS bilingue simulé avec succès (mode test)'
            ];
            $sms_success = true;
            $sms_message = $sms_result['message'];
        } else {
            // Envoi réel SMS
            $sms_result = sendSMS($client_phone, $sms_content, $BULKSMS_CONFIG);
            $sms_success = $sms_result['success'];
            $sms_message = $sms_success ? 'SMS envoyé avec succès' : ($sms_result['error'] ?? $sms_result['message']);
        }
        
        // Logger le résultat SMS
        logNotification($conn, $policy_id, 'sms_bilingue', $client_phone, 
                       $test_mode ? 'simulated' : ($sms_success ? 'sent' : 'failed'), 
                       $test_mode ? 'Mode test - SMS bilingue' : $sms_message);
        
        // Compter les résultats
        if ($sms_success) {
            $total_sent++;
            $results[] = [
                'policy' => $policy_number,
                'client' => $client_name,
                'phone' => $client_phone,
                'days' => $policy['days_until_expiry'],
                'status' => 'success',
                'message' => '✅ ' . $sms_message,
                'content' => $sms_content
            ];
        } else {
            $total_failed++;
            $results[] = [
                'policy' => $policy_number,
                'client' => $client_name,
                'phone' => $client_phone,
                'days' => $policy['days_until_expiry'],
                'status' => 'error',
                'message' => '❌ ' . $sms_message,
                'content' => $sms_content
            ];
        }
        
        // Délai entre envois pour éviter la surcharge
        if (!$test_mode) {
            usleep(1000000); // 1 seconde entre chaque SMS
        }
    }
}

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

// En mode automatique (cron), afficher seulement les logs texte
if ($auto_mode) {
    echo "NOTIFICATIONS SMS 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 SMS 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, #ff6b6b 0%, #ee5a24 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; }
        
        .sms-preview {
            background: #2d3748;
            color: #e2e8f0;
            padding: 15px;
            border-radius: 8px;
            font-family: monospace;
            font-size: 0.9rem;
            margin-top: 10px;
            white-space: pre-line;
        }
        
        .config-warning {
            background: #fef5e7;
            border: 1px solid #f6ad55;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            color: #744210;
        }
        
        .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 SMS Automatiques</h1>
            <p style="color: #718096; font-size: 1.1rem; margin-bottom: 20px;">
                Système d'envoi de rappels d'expiration par SMS 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">📱 SMS BulkSMS.ma</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>

        <!-- Configuration Warning -->
        <?php if ($BULKSMS_CONFIG['username'] === 'votre_username'): ?>
        <div class="config-warning">
            <strong>⚠️ Configuration requise :</strong> Veuillez configurer vos identifiants BulkSMS.ma dans les variables $BULKSMS_CONFIG (username et password).
        </div>
        <?php endif; ?>

        <!-- 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">SMS 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 SMS</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'): ?>
                        ✅ SMS Envoyé
                    <?php elseif ($result['status'] === 'skipped'): ?>
                        ⏭️ SMS Ignoré
                    <?php else: ?>
                        ❌ Échec SMS
                    <?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['phone']); ?><br>
                    💬 <?php echo htmlspecialchars($result['message']); ?>
                </div>
                
                <?php if (isset($result['content'])): ?>
                <div class="sms-preview">
                    <strong>📱 Aperçu du SMS :</strong>
                    <?php echo htmlspecialchars($result['content']); ?>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="results-section">
            <div style="text-align: center; color: #718096; padding: 40px;">
                🔍 Aucune notification SMS à envoyer aujourd'hui
            </div>
        </div>
        <?php endif; ?>

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

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

# Interface web
http://votre-domaine.com/hiba/notifications_sms_cron.php
            </div>
            
            <p><strong>Exemple de crontab (exécution quotidienne à 10h00) :</strong></p>
            <div class="url-examples">
0 10 * * * curl -s "http://votre-domaine.com/hiba/notifications_sms_cron.php?auto=1" >> /var/log/sms_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> 1 SMS bilingue court par client (FR + AR)<br>
                <strong>🔄 Anti-doublon :</strong> Maximum 1 SMS par jour par police<br>
                <strong>🌐 API :</strong> BulkSMS.ma (https://www.bulksms.ma/)<br>
                <strong>📊 Limite SMS :</strong> ~160 caractères recommandés
            </p>
              <div style="margin-top: 20px; padding: 15px; background: #e6fffa; border-radius: 8px; border-left: 4px solid #38b2ac;">
                <h4 style="color: #234e52; margin-bottom: 10px;">📱 Exemple de SMS bilingue :</h4>
                <div class="sms-preview" style="background: #234e52;">
Bonjour Ahmed Benali, votre assurance N°ABC123 va expirer le 25/07/2025. Veuillez passer chez nous pour la renouveler. Cordialement HIBA ASSURANCE.
---
مرحباً Ahmed Benali، تأمينكم رقم ABC123 سينتهي في 25/07/2025. يرجى زيارتنا لتجديده. مع التحية HIBA ASSURANCE.
                </div>
            </div>
        </div>
    </div>
</body>
</html>
