<?php

require_once __DIR__ . '/../database/db.php';
require_once __DIR__ . '/email_helper.php';

// Security: Require a secret token for web-based execution
$required_token = 'a9F3kP2xL8QwR7mZ'; // Change this!
if (php_sapi_name() !== 'cli') {
    // Running via web request
    if (!isset($_GET['token']) || $_GET['token'] !== $required_token) {
        http_response_code(403);
        die('Access denied');
    }
}

// Log start
$log_file = __DIR__ . '/logs/reminders.log';
$log_dir = dirname($log_file);
if (!is_dir($log_dir)) {
    mkdir($log_dir, 0755, true);
}

function logMessage($message) {
    global $log_file;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($log_file, "[$timestamp] $message\n", FILE_APPEND);
}

logMessage("=== Starting reminder email job ===");

try {
    // Find reminders that need to be sent
    // Get reminders where:
    // - reminder_time is in the past or within the next 5 minutes
    // - is_sent = 0
    $stmt = $pdo->prepare("
        SELECT 
            r.id as reminder_id,
            r.task_id,
            r.reminder_time,
            u.id as user_id,
            u.name as user_name,
            u.email as user_email,
            u.allow_email_notifications,
            t.title,
            t.description,
            t.start_datetime,
            t.color
        FROM reminders r
        JOIN tasks t ON r.task_id = t.id
        JOIN users u ON r.user_id = u.id
        WHERE r.is_sent = 0 
        AND r.reminder_time <= DATE_ADD(NOW(), INTERVAL 5 MINUTE)
        AND u.allow_email_notifications = 1
        ORDER BY r.reminder_time ASC
        LIMIT 100
    ");
    
    $stmt->execute();
    $reminders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $sent_count = 0;
    $failed_count = 0;
    
    foreach ($reminders as $reminder) {
        logMessage("Processing reminder #{$reminder['reminder_id']} for task: {$reminder['title']}");
        
        // Prepare task data
        $task_data = [
            'title' => $reminder['title'],
            'description' => $reminder['description'],
            'start_datetime' => $reminder['start_datetime'],
            'color' => $reminder['color']
        ];
        
        // Send email
        $email_sent = sendReminderEmail(
            $reminder['user_email'],
            $reminder['user_name'],
            $task_data,
            $reminder['reminder_time']
        );
        
        if ($email_sent) {
            // Mark reminder as sent
            $update_stmt = $pdo->prepare("UPDATE reminders SET is_sent = 1 WHERE id = ?");
            $update_stmt->execute([$reminder['reminder_id']]);
            
            $sent_count++;
            logMessage("✓ Email sent successfully to {$reminder['user_email']}");
        } else {
            $failed_count++;
            logMessage("✗ Failed to send email to {$reminder['user_email']}");
        }
        
        // Small delay to avoid overwhelming SMTP server
        usleep(500000); // 0.5 seconds
    }
    
    logMessage("=== Job completed: $sent_count sent, $failed_count failed ===");
    
    // Clean up old sent reminders (older than 30 days)
    $cleanup_stmt = $pdo->prepare("
        DELETE FROM reminders 
        WHERE is_sent = 1 
        AND reminder_time < DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    $cleanup_stmt->execute();
    $cleaned = $cleanup_stmt->rowCount();
    
    if ($cleaned > 0) {
        logMessage("Cleaned up $cleaned old reminders");
    }
    
    echo "Success: $sent_count emails sent, $failed_count failed\n";
    
} catch (Exception $e) {
    logMessage("ERROR: " . $e->getMessage());
    echo "Error: " . $e->getMessage() . "\n";
}