<?php
/**
 * ================================================
 * PARANDATUD MEELDETULETUSTE TÖÖTLEMINE - TÄPSE KELLAAJA TUGI
 * ================================================
 * 
 * Käivitamine:
 * CLI: php process_reminders.php --debug
 * WEB: process_reminders.php?debug=1
 * 
 * PARANDUSED:
 * - Täpse kellaaja tugi
 * - Parandatud debug
 * 
 * ================================================
 */

// Põhiseadistused - PARANDATUD TEED!
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';

// Email funktsioon (kui ei ole olemas)
if (!function_exists('sendEmail')) {
    require_once __DIR__ . '/../config/email.php';
}

// PARANDATUD: CLI ja Web debug käsitlemine
$isWeb = !empty($_SERVER['HTTP_HOST']);
$isCLI = php_sapi_name() === 'cli';

// Debug režiimi tuvastamine
$isDebug = false;
$isTest = false;

if ($isCLI) {
    // Terminal režiim
    $isTest = in_array('--test', $argv ?? []);
    $isDebug = in_array('--debug', $argv ?? []) || $isTest;
} else {
    // Browser režiim  
    $isTest = isset($_GET['test']) && $_GET['test'] == '1';
    $isDebug = isset($_GET['debug']) && $_GET['debug'] == '1' || $isTest;
}

// ALATI debug kui käivitatakse otse browseris
if ($isWeb && !isset($_GET['cron'])) {
    $isDebug = true;
}

// Web header
if ($isWeb) {
    header('Content-Type: text/html; charset=utf-8');
    echo "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>Meeldetuletuste töötlemine</title>";
    echo "<style>body{font-family:monospace;background:#1a1a1a;color:#fff;padding:20px;line-height:1.6;} .success{color:#0f0;} .error{color:#f00;} .warning{color:#fa0;} .info{color:#09f;}</style>";
    echo "</head><body><h1>🔔 Meeldetuletuste töötlemine</h1>";
}

// Log funktsioon - PARANDATUD
function reminderLog($message, $data = null, $force = false) {
    global $isDebug, $isWeb;
    
    $timestamp = date('Y-m-d H:i:s');
    $logEntry = "[$timestamp] REMINDER: $message";
    if ($data) {
        $logEntry .= ' | Data: ' . json_encode($data, JSON_UNESCAPED_UNICODE);
    }
    
    // Konsoolile/browseri väljastamine
    if ($isDebug || $force) {
        if ($isWeb) {
            $class = 'info';
            if (strpos($message, 'ERROR') !== false) $class = 'error';
            if (strpos($message, 'SUCCESS') !== false) $class = 'success';
            if (strpos($message, 'WARNING') !== false) $class = 'warning';
            
            echo "<div class='$class'>" . htmlspecialchars($logEntry) . "</div>\n";
            flush();
        } else {
            echo $logEntry . "\n";
        }
    }
    
    // Logi faili kirjutamine
    $logFile = __DIR__ . '/../../logs/reminders.log';
    
    // Loo logs kaust kui pole
    if (!is_dir(dirname($logFile))) {
        mkdir(dirname($logFile), 0755, true);
    }
    
    file_put_contents($logFile, $logEntry . "\n", FILE_APPEND | LOCK_EX);
}

/**
 * ================================================
 * DEBUG FUNKTSIOONID
 * ================================================
 */

function testDatabaseConnection($pdo) {
    reminderLog('🔍 Testing database connection...', null, true);
    
    try {
        // Test basic connection
        $stmt = $pdo->query("SELECT datetime('now') as current_time, datetime('now', 'localtime') as local_time");
        $result = $stmt->fetch();
        reminderLog('✅ Database connection SUCCESS', [
            'db_utc_time' => $result['current_time'],
            'db_local_time' => $result['local_time'],
            'php_time' => date('Y-m-d H:i:s')
        ], true);
        
        // Test reminder table
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM event_reminders");
        $count = $stmt->fetch()['count'];
        reminderLog('✅ Reminders table accessible', ['total_reminders' => $count], true);
        
        return true;
    } catch (Exception $e) {
        reminderLog('❌ Database connection FAILED', ['error' => $e->getMessage()], true);
        return false;
    }
}

function testEmailSystem() {
    reminderLog('🔍 Testing email system...', null, true);
    
    if (!function_exists('sendEmail')) {
        reminderLog('❌ ERROR: sendEmail function not found!', null, true);
        return false;
    }
    
    reminderLog('✅ sendEmail function found', null, true);
    
    // Email test on välja lülitatud
    reminderLog('ℹ️ Email sending test disabled for safety', null, true);
    return true;
}

function debugPendingReminders($pdo) {
    reminderLog('🔍 === DEBUGGING PENDING REMINDERS ===', null, true);
    
    try {
        // 1. Kõik meeldetuletused
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM event_reminders WHERE is_enabled = 1");
        $total = $stmt->fetch()['total'];
        reminderLog("📊 Total enabled reminders: $total", null, true);
        
        // 2. Saatmata meeldetuletused  
        $stmt = $pdo->query("SELECT COUNT(*) as unsent FROM event_reminders WHERE is_enabled = 1 AND sent_at IS NULL");
        $unsent = $stmt->fetch()['unsent'];
        reminderLog("📊 Unsent reminders: $unsent", null, true);
        
        // 3. Detailne päring - sama mis kasutab getPendingReminders
        $stmt = $pdo->prepare("
            SELECT 
                r.id as reminder_id,
                r.custom_message,
                r.reminder_datetime,
                r.minutes_before,
                r.sent_at,
                r.created_at,
                e.id as event_id,
                e.user_id,
                e.title as event_title,
                e.start_datetime as event_start,
                u.email as user_email,
                u.firstName,
                u.lastName,
                datetime('now') as current_utc_time,
                datetime('now', 'localtime') as current_local_time,
                (julianday(r.reminder_datetime) - julianday('now', 'localtime')) * 24 * 60 as minutes_until_reminder,
                (julianday(e.start_datetime) - julianday('now', 'localtime')) * 24 * 60 as minutes_until_event
            FROM event_reminders r
            INNER JOIN events e ON r.event_id = e.id
            INNER JOIN users u ON e.user_id = u.id
            WHERE r.is_enabled = 1 
            AND r.sent_at IS NULL
            ORDER BY r.reminder_datetime ASC
            LIMIT 10
        ");
        
        $stmt->execute();
        $allReminders = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        reminderLog("🔍 Found unsent reminders for analysis: " . count($allReminders), null, true);
        
        foreach ($allReminders as $reminder) {
            $shouldSendTime = $reminder['minutes_until_reminder'] <= 0;
            $eventInFuture = $reminder['minutes_until_event'] > 0;
            $hasEmail = !empty($reminder['user_email']);
            
            $canSend = $shouldSendTime && $eventInFuture && $hasEmail;
            
            $status = '❌ CANNOT SEND';
            if ($canSend) {
                $status = '✅ READY TO SEND';
            } elseif (!$shouldSendTime) {
                $status = '⏰ TOO EARLY (' . round($reminder['minutes_until_reminder'], 1) . ' min)';
            } elseif (!$eventInFuture) {
                $status = '⚠️ EVENT PASSED (' . round($reminder['minutes_until_event'], 1) . ' min ago)';
            } elseif (!$hasEmail) {
                $status = '📧 NO EMAIL';
            }
            
            reminderLog("📋 Reminder analysis:", [
                'id' => $reminder['reminder_id'],
                'message' => substr($reminder['custom_message'], 0, 50) . '...',
                'reminder_time' => $reminder['reminder_datetime'],
                'current_local' => $reminder['current_local_time'],
                'minutes_until_reminder' => round($reminder['minutes_until_reminder'], 1),
                'minutes_until_event' => round($reminder['minutes_until_event'], 1),
                'user_email' => $reminder['user_email'],
                'event_title' => $reminder['event_title'],
                'can_send' => $canSend,
                'status' => $status
            ], true);
        }
        
        // 4. Täpne sama päring mis kasutab getPendingReminders
        reminderLog('🔍 Testing exact getPendingReminders query...', null, true);
        
        $stmt = $pdo->prepare("
            SELECT 
                r.id as reminder_id,
                r.custom_message,
                r.reminder_datetime,
                r.minutes_before,
                r.is_recurring,
                r.recurring_type,
                r.recurring_interval,
                r.recurring_end_date,
                e.id as event_id,
                e.user_id,
                e.title as event_title,
                e.description as event_description,
                e.start_datetime as event_start,
                e.end_datetime as event_end,
                e.location as event_location,
                c.name as category_name,
                c.color as category_color,
                c.icon as category_icon,
                u.email as user_email,
                u.firstName,
                u.lastName
            FROM event_reminders r
            INNER JOIN events e ON r.event_id = e.id
            INNER JOIN users u ON e.user_id = u.id
            LEFT JOIN event_categories c ON e.category_id = c.id
            WHERE r.is_enabled = 1 
            AND r.sent_at IS NULL
            AND r.reminder_datetime <= datetime('now', 'localtime')
            AND e.start_datetime > datetime('now', 'localtime')
            AND u.email IS NOT NULL
            AND u.email != ''
            ORDER BY r.reminder_datetime ASC
            LIMIT 50
        ");
        
        $stmt->execute();
        $readyReminders = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        reminderLog("🎯 Reminders matching getPendingReminders criteria: " . count($readyReminders), null, true);
        
        foreach ($readyReminders as $reminder) {
            reminderLog("✅ Ready reminder:", [
                'id' => $reminder['reminder_id'],
                'message' => substr($reminder['custom_message'], 0, 50),
                'user' => $reminder['user_email'],
                'event' => $reminder['event_title']
            ], true);
        }
        
        return $readyReminders;
        
    } catch (Exception $e) {
        reminderLog('❌ Error debugging pending reminders', ['error' => $e->getMessage()], true);
        return [];
    }
}

/**
 * ================================================
 * PÕHIFUNKTSIOONID - SAMAD KUI ENNE
 * ================================================
 */

function getPendingReminders($pdo) {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                r.id as reminder_id,
                r.custom_message,
                r.reminder_datetime,
                r.minutes_before,
                r.is_recurring,
                r.recurring_type,
                r.recurring_interval,
                r.recurring_end_date,
                e.id as event_id,
                e.user_id,
                e.title as event_title,
                e.description as event_description,
                e.start_datetime as event_start,
                e.end_datetime as event_end,
                e.location as event_location,
                c.name as category_name,
                c.color as category_color,
                c.icon as category_icon,
                u.email as user_email,
                u.firstName,
                u.lastName
            FROM event_reminders r
            INNER JOIN events e ON r.event_id = e.id
            INNER JOIN users u ON e.user_id = u.id
            LEFT JOIN event_categories c ON e.category_id = c.id
            WHERE r.is_enabled = 1 
            AND r.sent_at IS NULL
            AND r.reminder_datetime <= datetime('now', 'localtime')
            AND e.start_datetime > datetime('now', 'localtime')
            AND u.email IS NOT NULL
            AND u.email != ''
            ORDER BY r.reminder_datetime ASC
            LIMIT 50
        ");
        
        $stmt->execute();
        $reminders = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        reminderLog('Found pending reminders', ['count' => count($reminders)]);
        return $reminders;
        
    } catch (PDOException $e) {
        reminderLog('Error loading pending reminders', ['error' => $e->getMessage()]);
        return [];
    }
}

function sendReminderEmail($pdo, $reminder) {
    global $isTest;
    
    try {
        // Kasutaja andmed
        $user = [
            'id' => $reminder['user_id'],
            'email' => $reminder['user_email'],
            'firstName' => $reminder['firstName'],
            'lastName' => $reminder['lastName'],
            'display_name' => trim($reminder['firstName'] . ' ' . $reminder['lastName']) ?: $reminder['user_email']
        ];
        
        if (!$user['email']) {
            reminderLog('User has no email', ['user_id' => $reminder['user_id']]);
            return false;
        }
        
        // Loo meilimall
        $subject = "🔔 Meeldetuletus: " . $reminder['event_title'];
        $html_body = "
        <h1>Meeldetuletus</h1>
        <p>Tere, {$user['display_name']}!</p>
        <p><strong>{$reminder['custom_message']}</strong></p>
        <p>Sündmus: <strong>{$reminder['event_title']}</strong></p>
        <p>Aeg: {$reminder['event_start']}</p>
        ";
        
        // TEST režiimis ära saada tegelikult
        if ($isTest) {
            reminderLog('TEST MODE: Would send email', [
                'to' => $user['email'],
                'subject' => $subject,
                'reminder_id' => $reminder['reminder_id']
            ], true);
            return true;
        }
        
        // Saada e-mail
        $sent = sendEmail($user['email'], $user['display_name'], $subject, $html_body);
        
        if ($sent) {
            // Märgi saadetud
            markReminderAsSent($pdo, $reminder['reminder_id']);
            
            reminderLog('Reminder sent successfully', [
                'reminder_id' => $reminder['reminder_id'],
                'user_email' => $user['email'],
                'event_title' => $reminder['event_title']
            ]);
            
            return true;
        } else {
            // Märgi viga
            markReminderError($pdo, $reminder['reminder_id'], 'Email sending failed');
            
            reminderLog('Failed to send reminder', [
                'reminder_id' => $reminder['reminder_id'],
                'user_email' => $user['email']
            ]);
            
            return false;
        }
        
    } catch (Exception $e) {
        markReminderError($pdo, $reminder['reminder_id'], $e->getMessage());
        reminderLog('Exception sending reminder', [
            'reminder_id' => $reminder['reminder_id'],
            'error' => $e->getMessage()
        ]);
        return false;
    }
}

function markReminderAsSent($pdo, $reminder_id) {
    try {
        $stmt = $pdo->prepare("
            UPDATE event_reminders 
            SET sent_at = datetime('now', 'localtime'), 
                sent_count = sent_count + 1,
                last_error = NULL,
                updated_at = datetime('now', 'localtime')
            WHERE id = ?
        ");
        return $stmt->execute([$reminder_id]);
    } catch (PDOException $e) {
        reminderLog('Error marking reminder as sent', ['error' => $e->getMessage()]);
        return false;
    }
}

function markReminderError($pdo, $reminder_id, $error) {
    try {
        $stmt = $pdo->prepare("
            UPDATE event_reminders 
            SET last_error = ?,
                updated_at = datetime('now', 'localtime')
            WHERE id = ?
        ");
        return $stmt->execute([$error, $reminder_id]);
    } catch (PDOException $e) {
        reminderLog('Error marking reminder error', ['error' => $e->getMessage()]);
        return false;
    }
}

/**
 * ================================================
 * PÕHIFUNKTSIOON - TÄIUSTATUD DEBUG-IGA
 * ================================================
 */

function processReminders($pdo) {
    global $isTest, $isDebug;
    
    reminderLog('Starting reminder processing', ['test_mode' => $isTest], true);
    
    // Debug süsteeme
    if ($isDebug) {
        testDatabaseConnection($pdo);
        testEmailSystem();
        $debugResults = debugPendingReminders($pdo);
        
        if (empty($debugResults)) {
            reminderLog('🚫 DEBUG: No reminders found that match sending criteria', null, true);
            reminderLog('ℹ️ Common reasons:', [
                'reminder_time_future' => 'Reminder time is in the future',
                'event_passed' => 'Event has already passed', 
                'no_email' => 'User has no email address',
                'already_sent' => 'Reminder already sent'
            ], true);
        }
    }
    
    // Lae saadetavad meeldetuletused
    $reminders = getPendingReminders($pdo);
    
    if (empty($reminders)) {
        reminderLog('No pending reminders found', null, true);
        return;
    }
    
    $sent_count = 0;
    $error_count = 0;
    
    foreach ($reminders as $reminder) {
        reminderLog('Processing reminder', [
            'reminder_id' => $reminder['reminder_id'],
            'event_title' => $reminder['event_title'],
            'user_email' => $reminder['user_email'],
            'reminder_time' => $reminder['reminder_datetime']
        ]);
        
        if (sendReminderEmail($pdo, $reminder)) {
            $sent_count++;
        } else {
            $error_count++;
        }
        
        // Väike paus et mitte ülekoormata
        if (!$isTest) {
            usleep(100000); // 0.1 sekundit
        }
    }
    
    reminderLog('Reminder processing completed', [
        'total_processed' => count($reminders),
        'sent_successfully' => $sent_count,
        'errors' => $error_count
    ], true);
}

/**
 * ================================================
 * KÄIVITAMINE
 * ================================================
 */

// Kui skript käivitatakse otse
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    
    reminderLog('=== REMINDER PROCESSING STARTED ===', [
        'timestamp' => date('Y-m-d H:i:s'),
        'timezone' => date_default_timezone_get(),
        'test_mode' => $isTest,
        'debug_mode' => $isDebug,
        'is_web' => $isWeb,
        'is_cli' => $isCLI
    ], true);
    
    try {
        // Töötle meeldetuletused
        processReminders($pdo);
        
        reminderLog('=== REMINDER PROCESSING COMPLETED ===', null, true);
        
    } catch (Exception $e) {
        reminderLog('FATAL ERROR in reminder processing', ['error' => $e->getMessage()], true);
        
        // Saada admin'ile veateavitus (kui mitte test režiimis)
        if (!$isTest && function_exists('sendEmail')) {
            sendEmail(
                'admin@estreka.ee', 
                'Estreka Admin', 
                'Viga kalendri meeldetuletustes',
                "Meeldetuletuste töötlemisel tekkis viga:\n\n" . $e->getMessage() . "\n\nAeg: " . date('Y-m-d H:i:s')
            );
        }
        
        if ($isWeb) {
            echo "<div class='error'>FATAL ERROR: " . htmlspecialchars($e->getMessage()) . "</div>";
        }
        
        exit(1);
    }
}

// Web footer
if ($isWeb) {
    echo "<br><a href='?debug=1'>🔄 Refresh</a> | <a href='?debug=1&test=1'>🧪 Test Mode</a> | <a href='../'>← Back</a>";
    echo "</body></html>";
}
?>