<?php
// Security check - ensure the user is authenticated
chdir('../');
include($_SERVER['DOCUMENT_ROOT'] . '/includes/include_all.inc.php');

// Check if user is logged in and has appropriate permissions
if(!isset($_SESSION['front_user_id']) || empty($_SESSION['front_user_id'])) {
    header('Content-Type: text/plain');
    echo "Unauthorized access";
    exit;
}

// Set proper headers for AJAX response
header('Content-Type: text/plain');

// Get the backup choice from POST
if (isset($_POST['backup_choice'])) {
    $backup_choice = $_POST['backup_choice'];
    
    // Set the flag file path
    $flag_file = '/home/anesoft/public_html/.push/execute_flag.txt';
    $log_file = '/home/anesoft/public_html/.push/execution_log.txt';
    
    // Create the flag file with the backup choice
    $result = file_put_contents($flag_file, $backup_choice);
    
    if ($result !== false) {
        echo "Script execution scheduled.\n";
        echo "Creating backup: " . ($backup_choice == 'y' ? 'Yes' : 'No') . "\n\n";
        
        // Initial wait for script to potentially start
        sleep(2);
        
        // Check if the log file exists and output its contents
        if (file_exists($log_file)) {
            echo "Execution log:\n";
            echo file_get_contents($log_file);
        } else {
            echo "Waiting for script execution to begin...\n";
            echo "The cron job should pick up your request shortly.\n";
            echo "This page will automatically refresh to show progress.\n";
            
            // Add a meta refresh tag with JavaScript for auto-refresh
            echo "\n\n<script>
                // Wait 10 seconds then refresh the content
                setTimeout(function() {
                    // Call the view log API to get the latest status
                    fetch('/api/view_log.php')
                        .then(response => response.text())
                        .then(data => {
                            // Replace the current output with the log content
                            document.getElementById('output').innerHTML = data;
                        });
                }, 10000);
            </script>";
        }
    } else {
        echo "Error: Failed to schedule script execution.\n";
        echo "Please check directory permissions or contact your administrator.\n";
    }
} else {
    echo "Error: No backup choice specified.\n";
}
?>