<?php
/**
 * AJAX Handler for Backup Status
 * Returns current backup status and Windows Task Scheduler information
 */

// Set JSON content type (only if headers not already sent)
if (!headers_sent()) {
    header('Content-Type: application/json');
}

try {
    // Suppress any warnings that might interfere with JSON output
    error_reporting(E_ERROR | E_PARSE);
    ini_set('display_errors', 0);
    
    // Change working directory to parent
    chdir(dirname(__DIR__));
    
    // Include database connection and timezone helper
    ob_start(); // Start output buffering to catch any warnings
    include 'db.php';
    require_once 'includes/timezone_helper.php';
    ob_end_clean(); // Clear any output
    
    // Set system timezone from settings
    setSystemTimezone();
    
    // Include the Windows Task Manager
    ob_start(); // Start output buffering to catch any warnings
    require_once 'handlers/windows_task_manager.php';
    ob_end_clean(); // Clear any output
    
    // Get date format from settings
    function getConfiguredDateFormat() {
        global $conn;
        
        $sql = "SELECT s.value, s.default_value 
                FROM settings s 
                JOIN setting_categories sc ON s.category_id = sc.id 
                WHERE sc.code = 'system_settings' AND s.code = 'date_display_format' 
                AND s.is_active = 1";
        
        $result = mysqli_query($conn, $sql);
        if ($result && mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_assoc($result);
            return $row['value'] ?: $row['default_value'];
        }
        
        // Fallback to default
        return 'Y-m-d';
    }
    
    // Get the configured date format
    $dateFormat = getConfiguredDateFormat();
    $dateTimeFormat = $dateFormat . ' H:i:s';
    
    // Load backup configuration
    $configFile = 'backup_config.json';
    $config = [];
    if (file_exists($configFile)) {
        $config = json_decode(file_get_contents($configFile), true) ?? [];
    }
    
    // Load last run data
    $lastRunFile = 'backup_last_run.json';
    $lastRun = [];
    if (file_exists($lastRunFile)) {
        $lastRun = json_decode(file_get_contents($lastRunFile), true) ?? [];
    }
    
    // Get Windows Task Scheduler status
    $taskManager = new WindowsTaskManager();
    $taskRunning = $taskManager->isTaskRunning();
    $taskStatus = $taskManager->getTaskStatus();
    
    // Get scheduler status
    $schedulerEnabled = $config['frequency']['enabled'] ?? false;
    $schedulerFrequency = $config['frequency']['type'] ?? 'unknown';
    
    // Calculate next backup time
    $nextBackup = 'Unknown';
    if ($schedulerEnabled && $taskRunning && !empty($lastRun)) {
        $nextBackup = calculateNextBackupTime($config, $lastRun, $dateTimeFormat);
    }
    
    // Helper function to calculate next backup time
    function calculateNextBackupTime($config, $lastRun, $dateTimeFormat) {
        $frequency = $config['frequency']['type'] ?? 'unknown';
        $now = time();
        
        switch ($frequency) {
            case '15min':
                $interval = 15 * 60;
                break;
            case '30min':
                $interval = 30 * 60;
                break;
            case 'hourly':
                $interval = 60 * 60;
                break;
            case '6hourly':
                $interval = 6 * 60 * 60;
                break;
            case '12hourly':
                $interval = 12 * 60 * 60;
                break;
            case 'daily':
                $backupTime = $config['frequency']['time'] ?? '02:00';
                $today = date('Y-m-d');
                $backupTimestamp = strtotime("{$today} {$backupTime}");
                if ($backupTimestamp <= $now) {
                    $backupTimestamp = strtotime("{$today} {$backupTime} +1 day");
                }
                return date($dateTimeFormat, $backupTimestamp);
            case 'weekly':
                $backupTime = $config['frequency']['time'] ?? '02:00';
                $nextSunday = strtotime("next Sunday {$backupTime}");
                if ($nextSunday <= $now) {
                    $nextSunday = strtotime("next Sunday {$backupTime} +1 week");
                }
                return date($dateTimeFormat, $nextSunday);
            default:
                return 'Unknown';
        }
        
        $lastBackupTime = $lastRun[$frequency] ?? 0;
        if ($lastBackupTime > 0) {
            $nextTime = $lastBackupTime + $interval;
            return date($dateTimeFormat, $nextTime);
        }
        
        return 'Unknown';
    }
    
    // Get last backup info
    $backupDir = $config['storage']['local_path'] ?? 'D:/wamp/backups/itrpos/';
    $lastBackup = 'Never';
    $lastBackupTime = 0;
    
    if (is_dir($backupDir)) {
        $files = glob($backupDir . 'itrpos_backup_*.sql*');
        if ($files) {
            $latestFile = '';
            $latestTime = 0;
            foreach ($files as $file) {
                $time = filemtime($file);
                if ($time > $latestTime) {
                    $latestTime = $time;
                    $latestFile = $file;
                }
            }
            if ($latestFile) {
                $lastBackup = date($dateTimeFormat, $latestTime);
                $lastBackupTime = $latestTime;
            }
        }
    }
    
    // Calculate time until next backup
    $timeUntilNext = 'Unknown';
    
    if ($nextBackup !== 'Unknown' && $nextBackup !== 'Never') {
        $nextTimestamp = strtotime($nextBackup);
        $now = time();
        $diff = $nextTimestamp - $now;
        
        if ($diff > 0) {
            $hours = floor($diff / 3600);
            $minutes = floor(($diff % 3600) / 60);
            
            if ($hours > 0) {
                $timeUntilNext = "{$hours}h {$minutes}m";
            } else {
                $timeUntilNext = "{$minutes}m";
            }
        } else {
            $timeUntilNext = "Overdue";
        }
    }
    
    // Determine overall status
    $overallStatus = 'Disabled';
    if ($schedulerEnabled && $taskRunning) {
        $overallStatus = 'Active';
    } else if ($schedulerEnabled && !$taskRunning) {
        $overallStatus = 'Configured';
    }
    
    // Return comprehensive status
    ob_start(); // Start output buffering for final JSON output
    echo json_encode([
        'success' => true,
        'scheduler' => [
            'enabled' => $schedulerEnabled,
            'working' => $taskRunning,
            'status' => $overallStatus,
            'frequency' => $schedulerFrequency
        ],
        'backups' => [
            'last_backup' => $lastBackup,
            'next_backup' => $nextBackup,
            'time_until_next' => $timeUntilNext,
            'last_runs' => $lastRun
        ],
        'windows_task' => [
            'running' => $taskRunning,
            'status' => $taskStatus,
            'exists' => $taskStatus['exists'] ?? false
        ],
        'configuration' => [
            'backup_enabled' => $config['frequency']['enabled'] ?? false,
            'backup_frequency' => $config['frequency']['type'] ?? 'unknown',
            'backup_time' => $config['frequency']['time'] ?? '02:00'
        ]
    ]);
    ob_end_flush(); // Send the buffered JSON output
    
} catch (Exception $e) {
    ob_start(); // Start output buffering for error JSON output
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'scheduler' => [
            'enabled' => false,
            'working' => false,
            'status' => 'Error',
            'frequency' => 'unknown'
        ],
        'backups' => [
            'last_backup' => 'Unknown',
            'next_backup' => 'Unknown',
            'time_until_next' => 'Unknown',
            'last_runs' => []
        ]
    ]);
    ob_end_flush(); // Send the buffered error JSON output
}
?>
