<?php
/**
 * Web-Based Cron Job Handler
 * This file should be called periodically (every minute) via a web request
 * It will check the config time and run notifications at the specified time
 * 
 * Setup:
 * 1. Set NOTIFICATION_TIME in config/config.php
 * 2. Call this URL every minute: http://localhost/birthday_reminder/cron/web_cron.php
 * 3. Or use Windows Task Scheduler to call this URL every minute
 */

// Set timezone to IST
date_default_timezone_set('Asia/Kolkata');

// Load configuration and autoloader
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/autoload.php';

// Security: Only allow execution from localhost or with secret key
$allowedIPs = ['127.0.0.1', '::1', 'localhost'];
$clientIP = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$secretKey = $_GET['key'] ?? '';

// Check if request is authorized
$isAuthorized = in_array($clientIP, $allowedIPs) || $secretKey === 'birthday_reminder_cron_2024';

if (!$isAuthorized) {
    http_response_code(403);
    die('Access denied. This cron job can only be run from localhost or with valid key.');
}

// Get current time
$currentTime = date('H:i');
$notificationTime = NOTIFICATION_TIME ?? '09:00';

// Log file for cron execution
$logFile = LOG_PATH . '/web_cron.log';

// Function to log cron activity
function logCron($message, $data = null) {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    $logMessage = "[$timestamp] $message";

    if ($data !== null) {
        $logMessage .= "\n" . json_encode($data, JSON_PRETTY_PRINT);
    }

    $logMessage .= "\n";

    file_put_contents($logFile, $logMessage, FILE_APPEND);

    // Also log to error.log for better debugging
    logError($message, $data);

    echo $logMessage;
}

logCron("Web cron executed. Current time: $currentTime, Notification time: $notificationTime");

// Check if it's time to send notifications
if ($currentTime === $notificationTime) {
    logCron("=== TIME MATCH! Starting notification process ===");
    logCron("Current time: $currentTime matches notification time: $notificationTime");

    try {
        // Create notification service
        logCron("Creating NotificationService instance...");
        $notificationService = new NotificationService();

        // Check service status
        $status = $notificationService->getStatus();
        logCron("Notification service status:", $status);

        // Send daily notifications
        logCron("Calling sendDailyReminders()...");
        $result = $notificationService->sendDailyReminders();

        // Log detailed results
        $sent = $result['sent'] ?? 0;
        $failed = $result['failed'] ?? 0;
        $skipped = $result['skipped'] ?? 0;

        logCron("=== NOTIFICATION RESULTS ===");
        logCron("Sent: $sent, Failed: $failed, Skipped: $skipped", $result);

        // Return JSON response
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'message' => 'Daily notifications sent',
            'time' => $currentTime,
            'stats' => $result
        ]);

    } catch (Exception $e) {
        logCron("=== ERROR OCCURRED ===");
        logCron("Exception: " . $e->getMessage());
        logCron("Stack trace: " . $e->getTraceAsString());

        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Failed to send notifications',
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);
    }
} else {
    logCron("Not time yet. Waiting for $notificationTime (current: $currentTime)");
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'message' => 'Cron executed but not time for notifications',
        'current_time' => $currentTime,
        'notification_time' => $notificationTime,
        'next_check' => 'Will check again in 1 minute'
    ]);
}
