<?php
/**
 * KDS Scheduled Cleanup Script
 * This script should be run via cron job for automatic cleanup
 * 
 * Example cron entry (runs daily at 2 AM):
 * 0 2 * * * /usr/bin/php /path/to/itrpos/kds_scheduled_cleanup.php >> /var/log/kds_cleanup.log 2>&1
 * 
 * Windows Task Scheduler:
 * Program: php.exe
 * Arguments: "D:\wamp\www\itrpos\kds_scheduled_cleanup.php"
 * Start in: D:\wamp\www\itrpos
 */

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

// Ensure this is only run 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);
}

// Include required files
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/kds_cleanup.php';

echo "=== KDS Scheduled Cleanup Started ===\n";
echo "Time: " . date('Y-m-d H:i:s') . "\n";
echo "Script: " . __FILE__ . "\n\n";

try {
    // Check if auto cleanup is enabled
    $auto_cleanup_result = $conn->query("SELECT value FROM settings WHERE code = 'kds_auto_cleanup_enabled'");
    if (!$auto_cleanup_result) {
        throw new Exception("Could not retrieve auto cleanup setting");
    }
    
    $auto_cleanup_setting = $auto_cleanup_result->fetch_assoc();
    $auto_cleanup_enabled = $auto_cleanup_setting && $auto_cleanup_setting['value'] === '1';
    
    if (!$auto_cleanup_enabled) {
        echo "Auto cleanup is disabled. Exiting.\n";
        exit(0);
    }
    
    echo "Auto cleanup is enabled. Proceeding...\n";
    
    // Get retention days setting
    $retention_result = $conn->query("SELECT value FROM settings WHERE code = 'kds_record_retention_days'");
    if (!$retention_result) {
        throw new Exception("Could not retrieve retention days setting");
    }
    
    $retention_setting = $retention_result->fetch_assoc();
    $retention_days = $retention_setting ? intval($retention_setting['value']) : 7;
    
    // Validate retention days
    if ($retention_days < 1 || $retention_days > 90) {
        throw new Exception("Invalid retention days: $retention_days. Must be between 1 and 90.");
    }
    
    echo "Retention period: $retention_days days\n";
    
    // Check if cleanup has already run today
    $today = date('Y-m-d');
    $last_cleanup_check = $conn->query("
        SELECT COUNT(*) as count 
        FROM kds_cleanup_log 
        WHERE DATE(cleanup_date) = '$today' 
        AND status = 'success'
    ");
    
    if ($last_cleanup_check) {
        $last_cleanup_data = $last_cleanup_check->fetch_assoc();
        if ($last_cleanup_data['count'] > 0) {
            echo "Cleanup already performed today. Skipping.\n";
            exit(0);
        }
    }
    
    echo "Starting cleanup process...\n";
    
    // Perform the cleanup
    $result = performKDSCleanup($conn, $retention_days, false);
    
    if ($result['success']) {
        echo "✅ Cleanup completed successfully!\n";
        echo "• Orders deleted: " . $result['orders_deleted'] . "\n";
        echo "• Order items deleted: " . $result['order_items_deleted'] . "\n";
        echo "• Activity logs deleted: " . $result['activity_logs_deleted'] . "\n";
        echo "• Total records deleted: " . $result['total_records_deleted'] . "\n";
        echo "• Execution time: " . $result['execution_time_ms'] . "ms\n";
        
        // Update last cleanup date in settings
        $timestamp = date('Y-m-d H:i:s');
        $update_stmt = $conn->prepare("UPDATE settings SET value = ? WHERE code = 'kds_last_cleanup_date'");
        $update_stmt->bind_param("s", $timestamp);
        $update_stmt->execute();
        $update_stmt->close();
        
        echo "Last cleanup date updated: $timestamp\n";
        
    } else {
        echo "❌ Cleanup failed!\n";
        echo "Error: " . $result['message'] . "\n";
        exit(1);
    }
    
} catch (Exception $e) {
    echo "❌ Script error: " . $e->getMessage() . "\n";
    
    // Log the error to cleanup log if possible
    try {
        $error_stmt = $conn->prepare("
            INSERT INTO kds_cleanup_log 
            (retention_days, status, message) 
            VALUES (?, 'failed', ?)
        ");
        $error_message = "Scheduled cleanup script error: " . $e->getMessage();
        $error_stmt->bind_param("is", $retention_days ?? 7, $error_message);
        $error_stmt->execute();
        $error_stmt->close();
    } catch (Exception $log_error) {
        echo "Could not log error to database: " . $log_error->getMessage() . "\n";
    }
    
    exit(1);
}

echo "\n=== KDS Scheduled Cleanup Completed ===\n";
echo "End time: " . date('Y-m-d H:i:s') . "\n";

exit(0);
?>
