<?php
/**
 * ITRPOS Automated Backup Scheduler
 * Runs via Windows Task Scheduler and creates backups based on configuration
 */

// Ensure this script only runs from command line
if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    echo "This script can only be run from command line\n";
    exit(1);
}

// Set error reporting for CLI
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Set execution time limit
set_time_limit(300); // 5 minutes

// Change to script directory and ensure we're in the right place
chdir(__DIR__);

// Verify we're in the correct directory by checking for required files
if (!file_exists('db.php') || !file_exists('backup_engine.php')) {
    // Try to find the correct directory
    $possibleDirs = [
        __DIR__,
        dirname(__DIR__),
        getcwd()
    ];
    
    foreach ($possibleDirs as $dir) {
        if (file_exists($dir . DIRECTORY_SEPARATOR . 'db.php') && 
            file_exists($dir . DIRECTORY_SEPARATOR . 'backup_engine.php')) {
            chdir($dir);
            break;
        }
    }
}

// Include database connection and timezone helper
include 'db.php';
require_once 'includes/timezone_helper.php';

// Set system timezone from settings
setSystemTimezone();

// Include required files
require_once 'backup_engine.php';

class BackupScheduler {
    private $configFile = 'backup_config.json';
    private $lastRunFile = 'backup_last_run.json';
    private $config;
    private $lastRun;
    
    public function __construct() {
        $this->loadConfiguration();
        $this->loadLastRunData();
    }
    
    private function loadConfiguration() {
        if (!file_exists($this->configFile)) {
            $this->log("Backup configuration file not found: {$this->configFile}", 'ERROR');
            exit(1);
        }
        
        $this->config = json_decode(file_get_contents($this->configFile), true);
        if (!$this->config) {
            $this->log("Invalid backup configuration file", 'ERROR');
            exit(1);
        }
        
        // Check if automated backups are enabled
        if (!isset($this->config['frequency']['enabled']) || !$this->config['frequency']['enabled']) {
            $this->log("Automated backups are disabled in configuration", 'INFO');
            exit(0);
        }
    }
    
    private function loadLastRunData() {
        $this->lastRun = [];
        if (file_exists($this->lastRunFile)) {
            $this->lastRun = json_decode(file_get_contents($this->lastRunFile), true) ?? [];
        }
    }
    
    private function saveLastRunData() {
        file_put_contents($this->lastRunFile, json_encode($this->lastRun, JSON_PRETTY_PRINT));
    }
    
    public function checkAndRunBackup() {
        $frequency = $this->config['frequency']['type'];
        $now = time();
        
        $this->log("Checking backup schedule for frequency: {$frequency}", 'DEBUG');
        
        // Check if it's time for a backup
        if ($this->shouldRunBackup($frequency, $now)) {
            $this->log("Time for scheduled backup: {$frequency}", 'INFO');
            $this->runScheduledBackup($frequency);
        } else {
            $this->log("Not time for backup yet", 'DEBUG');
        }
    }
    
    private function shouldRunBackup($frequency, $now) {
        $lastBackupTime = $this->lastRun[$frequency] ?? 0;
        $interval = $this->getBackupInterval($frequency);
        
        if ($interval === 0) {
            return false; // Invalid frequency
        }
        
        // Check if enough time has passed since last backup
        return ($now - $lastBackupTime) >= $interval;
    }
    
    private function getBackupInterval($frequency) {
        switch ($frequency) {
            case '15min':
                return 15 * 60; // 15 minutes
            case '30min':
                return 30 * 60; // 30 minutes
            case 'hourly':
                return 60 * 60; // 1 hour
            case '6hourly':
                return 6 * 60 * 60; // 6 hours
            case '12hourly':
                return 12 * 60 * 60; // 12 hours
            case 'daily':
                return $this->getDailyInterval();
            case 'weekly':
                return $this->getWeeklyInterval();
            default:
                $this->log("Unknown backup frequency: {$frequency}", 'WARNING');
                return 0;
        }
    }
    
    private function getDailyInterval() {
        $backupTime = $this->config['frequency']['time'] ?? '02:00';
        $now = time();
        $today = date('Y-m-d');
        $backupTimestamp = strtotime("{$today} {$backupTime}");
        
        // If backup time has passed today, schedule for tomorrow
        if ($backupTimestamp <= $now) {
            $backupTimestamp = strtotime("{$today} {$backupTime} +1 day");
        }
        
        return $backupTimestamp - $now;
    }
    
    private function getWeeklyInterval() {
        $backupTime = $this->config['frequency']['time'] ?? '02:00';
        $now = time();
        $today = date('Y-m-d');
        
        // Find next Sunday at backup time
        $nextSunday = strtotime("next Sunday {$backupTime}");
        if ($nextSunday <= $now) {
            $nextSunday = strtotime("next Sunday {$backupTime} +1 week");
        }
        
        return $nextSunday - $now;
    }
    
    private function runScheduledBackup($type) {
        try {
            $this->log("Starting scheduled backup: {$type}", 'INFO');
            
            // Create backup engine instance
            $engine = new DatabaseBackupEngine();
            
            // Run the backup
            $result = $engine->createBackup($type);
            
            if ($result['success']) {
                $this->log("Scheduled backup completed successfully: {$result['filename']}", 'SUCCESS');
                
                // Update last run time
                $this->lastRun[$type] = time();
                $this->saveLastRunData();
                
                // Log backup details
                $this->log("Backup details - Size: {$result['size']}, Duration: {$result['duration']}s", 'INFO');
                
            } else {
                $this->log("Scheduled backup failed: {$result['message']}", 'ERROR');
            }
            
        } catch (Exception $e) {
            $this->log("Scheduled backup exception: " . $e->getMessage(), 'ERROR');
        }
    }
    
    private function log($message, $level = 'INFO') {
        $timestamp = date('Y-m-d H:i:s');
        $logEntry = "[{$timestamp}] [{$level}] {$message}" . PHP_EOL;
        
        // Output to console
        echo $logEntry;
        
        // Also log to file if backup directory exists
        $config = $this->config;
        if (isset($config['storage']['local_path'])) {
            $logFile = $config['storage']['local_path'] . 'scheduler_log.txt';
            file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        }
    }
}

// Main execution
try {
    $scheduler = new BackupScheduler();
    $scheduler->checkAndRunBackup();
    
} catch (Exception $e) {
    echo "[" . date('Y-m-d H:i:s') . "] [ERROR] Scheduler failed: " . $e->getMessage() . "\n";
    exit(1);
}
?>
