<?php
/**
 * Test Script for Cancel Pending Bookings Cron Job
 * 
 * This script helps test the cron job functionality by:
 * 1. Creating test pending appointments
 * 2. Running the cancellation process
 * 3. Verifying results
 */

require_once '../config/database.php';

// Set timezone
date_default_timezone_set('Asia/Kolkata');

echo "<h2>Testing Cancel Pending Bookings Cron Job</h2>";

try {
    $pdo = getDBConnection();
    
    // Test 1: Check current pending appointments
    echo "<h3>1. Current Pending Appointments</h3>";
    $query = "SELECT COUNT(*) as count FROM appointments WHERE status = 'pending'";
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $currentPending = $stmt->fetch(PDO::FETCH_ASSOC);
    echo "Current pending appointments: " . $currentPending['count'] . "<br>";
    
    // Test 2: Check old pending appointments (>10 minutes)
    echo "<h3>2. Old Pending Appointments (>10 minutes)</h3>";
    $tenMinutesAgo = date('Y-m-d H:i:s', strtotime('-10 minutes'));
    $query = "
        SELECT id, user_name, user_mobile, created_at, 
               TIMESTAMPDIFF(MINUTE, created_at, NOW()) as age_minutes
        FROM appointments 
        WHERE status = 'pending' 
        AND created_at < ?
        ORDER BY created_at ASC
    ";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$tenMinutesAgo]);
    $oldPending = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "Old pending appointments: " . count($oldPending) . "<br>";
    if (!empty($oldPending)) {
        echo "<table border='1' style='border-collapse: collapse; margin: 10px 0;'>";
        echo "<tr><th>ID</th><th>Name</th><th>Mobile</th><th>Created</th><th>Age (minutes)</th></tr>";
        foreach ($oldPending as $appointment) {
            echo "<tr>";
            echo "<td>{$appointment['id']}</td>";
            echo "<td>{$appointment['user_name']}</td>";
            echo "<td>{$appointment['user_mobile']}</td>";
            echo "<td>{$appointment['created_at']}</td>";
            echo "<td>{$appointment['age_minutes']}</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    
    // Test 3: Create test appointments (if needed)
    echo "<h3>3. Creating Test Appointments (if needed)</h3>";
    if (count($oldPending) < 2) {
        echo "Creating test appointments...<br>";
        
        // Create a test appointment that's 15 minutes old
        $fifteenMinutesAgo = date('Y-m-d H:i:s', strtotime('-15 minutes'));
        $testQuery = "
            INSERT INTO appointments (user_id, user_name, user_mobile, appointment_date, time_slot, amount, status, consultation_type, created_at)
            VALUES (1, 'Test User 1', '9999999999', CURDATE(), '10:00 AM - 11:00 AM', 500.00, 'pending', 'video_call', ?)
        ";
        $stmt = $pdo->prepare($testQuery);
        $stmt->execute([$fifteenMinutesAgo]);
        echo "Created test appointment 15 minutes old<br>";
        
        // Create another test appointment that's 20 minutes old
        $twentyMinutesAgo = date('Y-m-d H:i:s', strtotime('-20 minutes'));
        $testQuery = "
            INSERT INTO appointments (user_id, user_name, user_mobile, appointment_date, time_slot, amount, status, consultation_type, created_at)
            VALUES (1, 'Test User 2', '9999999998', CURDATE(), '11:00 AM - 12:00 PM', 500.00, 'pending', 'audio_call', ?)
        ";
        $stmt = $pdo->prepare($testQuery);
        $stmt->execute([$twentyMinutesAgo]);
        echo "Created test appointment 20 minutes old<br>";
    } else {
        echo "Test appointments already exist<br>";
    }
    
    // Test 4: Run the cron job
    echo "<h3>4. Running Cron Job</h3>";
    echo "<a href='cancel_pending_bookings.php?run_cron=1' target='_blank'>Click here to run the cron job</a><br>";
    echo "Or run this command in terminal: <code>php cancel_pending_bookings.php</code><br>";
    
    // Test 5: Check results after running
    echo "<h3>5. After Running Cron Job</h3>";
    echo "Check the results by refreshing this page or running the cron job manually.<br>";
    
    // Test 6: Show cron job setup instructions
    echo "<h3>6. Cron Job Setup Instructions</h3>";
    echo "<div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 10px 0;'>";
    echo "<h4>For Linux/Unix servers:</h4>";
    echo "<code>*/5 * * * * /usr/bin/php " . __DIR__ . "/cancel_pending_bookings.php</code><br><br>";
    
    echo "<h4>For Windows (using Task Scheduler):</h4>";
    echo "1. Open Task Scheduler<br>";
    echo "2. Create Basic Task<br>";
    echo "3. Set trigger to 'Daily' and repeat every 5 minutes<br>";
    echo "4. Set action to 'Start a program'<br>";
    echo "5. Program: <code>php.exe</code><br>";
    echo "6. Arguments: <code>" . __DIR__ . "/cancel_pending_bookings.php</code><br>";
    echo "</div>";
    
    // Test 7: Show log file location
    echo "<h3>7. Log File</h3>";
    $logFile = '../logs/cron_cancel_bookings.log';
    echo "Log file location: <code>$logFile</code><br>";
    if (file_exists($logFile)) {
        echo "Log file exists. Last 10 lines:<br>";
        echo "<pre style='background: #f8f9fa; padding: 10px; border-radius: 5px; max-height: 200px; overflow-y: auto;'>";
        $lines = file($logFile);
        $lastLines = array_slice($lines, -10);
        echo htmlspecialchars(implode('', $lastLines));
        echo "</pre>";
    } else {
        echo "Log file doesn't exist yet. It will be created when the cron job runs.<br>";
    }
    
} catch (Exception $e) {
    echo "<div style='color: red; background: #ffe6e6; padding: 10px; border-radius: 5px;'>";
    echo "<strong>Error:</strong> " . $e->getMessage();
    echo "</div>";
}

echo "<br><a href='appointments.php'>← Back to Appointments</a>";
?>
