<?php
/**
 * Simple Backup Status Handler
 * Minimal version without complex includes to avoid HTTP errors
 */

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

// Suppress all errors and warnings
error_reporting(0);
ini_set('display_errors', 0);

try {
    // Change working directory to parent
    chdir(dirname(__DIR__));
    
    // 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 scheduler status
    $schedulerEnabled = $config['frequency']['enabled'] ?? false;
    $schedulerFrequency = $config['frequency']['type'] ?? 'unknown';
    
    // Simple Windows Task Scheduler check (without complex includes)
    $taskRunning = false;
    $taskExists = false;
    
    // Try to check if Windows Task Scheduler is available
    if (function_exists('exec')) {
        $output = [];
        $returnCode = 0;
        exec('schtasks /query /tn "ITRPOS Backup Scheduler" /fo csv 2>&1', $output, $returnCode);
        if ($returnCode === 0 && !empty($output)) {
            $taskExists = true;
            $outputString = implode("\n", $output);
            if (strpos($outputString, 'Ready') !== false) {
                $taskRunning = true;
            }
        }
    }
    
    // Calculate next backup time (simplified)
    $nextBackup = 'Unknown';
    if ($schedulerEnabled && $taskRunning && !empty($lastRun)) {
        $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':
                // For daily backups, calculate next backup at configured time
                $backupTime = $config['frequency']['time'] ?? '02:00';
                $today = date('Y-m-d');
                $backupTimestamp = strtotime("{$today} {$backupTime}");
                if ($backupTimestamp <= $now) {
                    $backupTimestamp = strtotime("{$today} {$backupTime} +1 day");
                }
                $nextBackup = date('Y-m-d H:i:s', $backupTimestamp);
                break;
            case 'weekly':
                // For weekly backups, calculate next Sunday at configured time
                $backupTime = $config['frequency']['time'] ?? '02:00';
                $nextSunday = strtotime("next Sunday {$backupTime}");
                if ($nextSunday <= $now) {
                    $nextSunday = strtotime("next Sunday {$backupTime} +1 week");
                }
                $nextBackup = date('Y-m-d H:i:s', $nextSunday);
                break;
            default:
                $interval = 0;
        }
        
        // Only calculate interval-based next backup if not already set (for daily/weekly)
        if ($nextBackup === 'Unknown' && $interval > 0) {
            $lastBackupTime = $lastRun[$frequency] ?? 0;
            
            // If no last run for this frequency, try to use the most recent backup time
            if ($lastBackupTime === 0 && !empty($lastRun)) {
                $lastBackupTime = max($lastRun);
            }
            
            // If still no last run time, use current time minus interval (so next backup is soon)
            if ($lastBackupTime === 0) {
                $lastBackupTime = $now - $interval;
            }
            
            $nextTime = $lastBackupTime + $interval;
            $nextBackup = date('Y-m-d H:i:s', $nextTime);
        }
    }
    
    // Get last backup info
    $backupDir = $config['storage']['local_path'] ?? 'D:/wamp/backups/itrpos/';
    $lastBackup = 'Never';
    
    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('Y-m-d H:i:s', $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
    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' => [
                'exists' => $taskExists,
                'status' => $taskRunning ? 'Ready' : 'Not Found'
            ],
            'exists' => $taskExists
        ],
        'configuration' => [
            'backup_enabled' => $config['frequency']['enabled'] ?? false,
            'backup_frequency' => $config['frequency']['type'] ?? 'unknown',
            'backup_time' => $config['frequency']['time'] ?? '02:00'
        ]
    ]);
    
} catch (Exception $e) {
    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' => []
        ]
    ]);
}
?>
