<?php
/**
 * Manual Windows Task Scheduler Setup
 * Run this script as Administrator to create the backup task
 */

// Check if running as administrator
function isRunningAsAdmin() {
    if (function_exists('exec')) {
        $output = [];
        $returnCode = 0;
        exec('net session 2>&1', $output, $returnCode);
        return $returnCode === 0;
    }
    return false;
}

echo "=== ITRPOS Backup - Manual Windows Task Scheduler Setup ===\n\n";

if (!isRunningAsAdmin()) {
    echo "❌ ERROR: This script must be run as Administrator!\n";
    echo "Please right-click on Command Prompt and select 'Run as administrator',\n";
    echo "then navigate to this directory and run: php setup_windows_task_manual.php\n\n";
    echo "Alternatively, you can manually create the task using the command below:\n\n";
} else {
    echo "✅ Running as Administrator - Proceeding with setup...\n\n";
}

// Load Windows Task Manager
require_once 'handlers/windows_task_manager.php';
$taskManager = new WindowsTaskManager();

echo "=== System Information ===\n";
$systemInfo = $taskManager->getSystemInfo();
echo "PHP Path: " . $systemInfo['php_path'] . "\n";
echo "Script Path: " . $systemInfo['script_path'] . "\n";
echo "Task Name: " . $systemInfo['task_name'] . "\n\n";

// Check if task already exists
$existingStatus = $taskManager->getTaskStatus();
if ($existingStatus['exists']) {
    echo "⚠️  WARNING: Task already exists!\n";
    echo "Removing existing task first...\n";
    $removeResult = $taskManager->removeBackupTask();
    if ($removeResult['success']) {
        echo "✅ Existing task removed successfully\n\n";
    } else {
        echo "❌ Failed to remove existing task: " . $removeResult['message'] . "\n\n";
    }
}

echo "=== Creating Windows Task Scheduler Task ===\n";
$result = $taskManager->createBackupTask();

if ($result['success']) {
    echo "✅ SUCCESS: Windows Task Scheduler task created successfully!\n";
    echo "Message: " . $result['message'] . "\n\n";
    
    echo "=== Verifying Task Creation ===\n";
    $status = $taskManager->getTaskStatus();
    if ($status['exists']) {
        echo "✅ Task verified and exists in Windows Task Scheduler\n";
        echo "Status: " . json_encode($status['status'], JSON_PRETTY_PRINT) . "\n\n";
        
        echo "=== Testing Backup Status ===\n";
        // Test the backup status
        $statusOutput = shell_exec('php ajax/backup_status_simple.php 2>&1');
        $statusData = json_decode($statusOutput, true);
        
        if ($statusData && $statusData['success']) {
            echo "✅ Backup status working correctly\n";
            echo "Windows Task Scheduler: " . ($statusData['windows_task']['running'] ? 'Active' : 'Configured') . "\n";
            echo "Next Backup: " . $statusData['backups']['next_backup'] . "\n";
            echo "Time Until Next: " . $statusData['backups']['time_until_next'] . "\n";
            echo "Frequency: " . $statusData['configuration']['backup_frequency'] . "\n\n";
        } else {
            echo "⚠️  Backup status test failed\n";
        }
        
        echo "🎉 SETUP COMPLETE! Your automated backup system is now working!\n";
        echo "The system will automatically create backups according to your configured schedule.\n";
        
    } else {
        echo "❌ Task creation reported success but task doesn't exist\n";
    }
    
} else {
    echo "❌ FAILED: Could not create Windows Task Scheduler task\n";
    echo "Error: " . $result['message'] . "\n";
    echo "Solution: " . ($result['solution'] ?? 'Please check system permissions') . "\n\n";
    
    echo "=== Manual Command ===\n";
    echo "You can manually create the task by running this command as Administrator:\n\n";
    echo "schtasks /create /tn \"ITRPOS Backup Scheduler\" /tr \"\\\"" . $systemInfo['php_path'] . "\\\" \\\"" . $systemInfo['script_path'] . "\\\"\" /sc minute /mo 1 /f\n\n";
    
    echo "=== Alternative: Run WAMP as Administrator ===\n";
    echo "1. Close WAMP completely\n";
    echo "2. Right-click on WAMP icon and select 'Run as administrator'\n";
    echo "3. Go to backup management page and save configuration again\n";
    echo "4. The task should be created automatically\n\n";
}

echo "=== Setup Complete ===\n";
?>
