<?php
/**
 * Cron Job Setup Helper
 * 
 * This script helps set up the cron job for cancelling pending bookings
 */

$page_title = 'Cron Job Setup';
$current_page = 'setup_cron_job.php';

// Check if admin is logged in
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

ob_start();
?>

<div class="content-card">
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4 gap-3">
        <h2 class="mb-0"><i class="fas fa-clock me-2"></i>Cron Job Setup</h2>
        <div class="d-flex gap-2">
            <a href="test_cron_job.php" class="btn btn-info">
                <i class="fas fa-vial me-2"></i>Test Cron Job
            </a>
            <a href="cancel_pending_bookings.php" class="btn btn-warning">
                <i class="fas fa-play me-2"></i>Run Manually
            </a>
        </div>
    </div>
    
    <div class="alert alert-info">
        <h5><i class="fas fa-info-circle me-2"></i>Available Cron Jobs</h5>
        <p class="mb-0">
            <strong>1. Cancel Pending Bookings:</strong> Automatically cancels appointments that have been pending for more than 10 minutes.<br>
            <strong>2. Complete Confirmed Appointments:</strong> Automatically completes confirmed appointments whose appointment time has passed.
        </p>
    </div>
    
    <!-- Tabs for different cron jobs -->
    <ul class="nav nav-tabs mb-4" id="cronTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="cancel-tab" data-bs-toggle="tab" data-bs-target="#cancel" type="button" role="tab">
                <i class="fas fa-times-circle me-2"></i>Cancel Pending Bookings
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="complete-tab" data-bs-toggle="tab" data-bs-target="#complete" type="button" role="tab">
                <i class="fas fa-check-circle me-2"></i>Complete Confirmed Appointments
            </button>
        </li>
    </ul>
    
    <div class="tab-content" id="cronTabsContent">
        <!-- Cancel Pending Bookings Tab -->
        <div class="tab-pane fade show active" id="cancel" role="tabpanel">
    
    <!-- Current Status -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card bg-light">
                <div class="card-body text-center">
                    <h3 class="text-primary" id="totalPending">-</h3>
                    <p class="mb-0">Total Pending Appointments</p>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card bg-light">
                <div class="card-body text-center">
                    <h3 class="text-warning" id="oldPending">-</h3>
                    <p class="mb-0">Old Pending (>10 minutes)</p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Setup Instructions -->
    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0"><i class="fas fa-linux me-2"></i>Linux/Unix Setup</h5>
                </div>
                <div class="card-body">
                    <h6>Step 1: Open Crontab</h6>
                    <code>crontab -e</code>
                    
                    <h6 class="mt-3">Step 2: Add This Line</h6>
                    <div class="bg-dark text-light p-3 rounded">
                        <code>*/5 * * * * /usr/bin/php <?php echo __DIR__; ?>/cancel_pending_bookings.php</code>
                    </div>
                    
                    <h6 class="mt-3">Step 3: Save and Exit</h6>
                    <p>Press <kbd>Ctrl + X</kbd>, then <kbd>Y</kbd>, then <kbd>Enter</kbd></p>
                    
                    <h6 class="mt-3">Step 4: Verify</h6>
                    <code>crontab -l</code>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fab fa-windows me-2"></i>Windows Setup</h5>
                </div>
                <div class="card-body">
                    <h6>Step 1: Open Task Scheduler</h6>
                    <p>Search "Task Scheduler" in Start Menu</p>
                    
                    <h6 class="mt-3">Step 2: Create Basic Task</h6>
                    <p>Right-click → "Create Basic Task"</p>
                    
                    <h6 class="mt-3">Step 3: Configure</h6>
                    <ul>
                        <li><strong>Name:</strong> Cancel Pending Bookings</li>
                        <li><strong>Trigger:</strong> Daily, repeat every 5 minutes</li>
                        <li><strong>Action:</strong> Start a program</li>
                        <li><strong>Program:</strong> <code>php.exe</code></li>
                        <li><strong>Arguments:</strong> <code><?php echo __DIR__; ?>/cancel_pending_bookings.php</code></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Manual Testing -->
    <div class="card mt-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-vial me-2"></i>Manual Testing</h5>
        </div>
        <div class="card-body">
            <p>Before setting up the cron job, test it manually:</p>
            
            <div class="d-grid gap-2 d-md-flex">
                <button class="btn btn-warning" onclick="runCronJob()">
                    <i class="fas fa-play me-2"></i>Run Cron Job Now
                </button>
                <button class="btn btn-info" onclick="refreshStats()">
                    <i class="fas fa-refresh me-2"></i>Refresh Statistics
                </button>
                <a href="test_cron_job.php" class="btn btn-secondary">
                    <i class="fas fa-vial me-2"></i>Test Script
                </a>
            </div>
            
            <div id="result" class="mt-3"></div>
        </div>
    </div>
    
    <!-- Log File -->
    <div class="card mt-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-file-alt me-2"></i>Log File</h5>
        </div>
        <div class="card-body">
            <p>Monitor the cron job execution through the log file:</p>
            <code><?php echo __DIR__; ?>/../logs/cron_cancel_bookings.log</code>
            
            <div class="mt-3">
                <button class="btn btn-sm btn-outline-primary" onclick="viewLog()">
                    <i class="fas fa-eye me-2"></i>View Log
                </button>
                <button class="btn btn-sm btn-outline-danger" onclick="clearLog()">
                    <i class="fas fa-trash me-2"></i>Clear Log
                </button>
            </div>
            
            <div id="logContent" class="mt-3" style="display: none;">
                <pre id="logText" style="background: #f8f9fa; padding: 15px; border-radius: 5px; max-height: 300px; overflow-y: auto;"></pre>
            </div>
        </div>
    </div>
    
    <!-- Troubleshooting -->
    <div class="card mt-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-tools me-2"></i>Troubleshooting</h5>
        </div>
        <div class="card-body">
            <h6>Common Issues:</h6>
            <ul>
                <li><strong>Cron job not running:</strong> Check if PHP path is correct (<code>which php</code>)</li>
                <li><strong>Permission denied:</strong> Make sure the script has execute permissions</li>
                <li><strong>Database connection failed:</strong> Check database configuration</li>
                <li><strong>Log file not created:</strong> Check if logs directory is writable</li>
            </ul>
            
            <h6 class="mt-3">Test Commands:</h6>
            <div class="bg-dark text-light p-3 rounded">
                <code>
                    # Test PHP path<br>
                    which php<br><br>
                    # Test script execution<br>
                    php <?php echo __DIR__; ?>/cancel_pending_bookings.php<br><br>
                    # Check cron job status<br>
                    crontab -l
                </code>
            </div>
        </div>
    </div>
    
    <!-- Complete Confirmed Appointments Tab -->
    <div class="tab-pane fade" id="complete" role="tabpanel">
        <div class="alert alert-success">
            <h5><i class="fas fa-check-circle me-2"></i>Complete Confirmed Appointments Cron Job</h5>
            <p class="mb-0">This cron job automatically completes confirmed appointments whose appointment time (end time of time slot) has passed. This ensures appointments are marked as completed after they finish.</p>
        </div>
        
        <!-- Current Status -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card bg-light">
                    <div class="card-body text-center">
                        <h3 class="text-success" id="totalConfirmed">-</h3>
                        <p class="mb-0">Total Confirmed Appointments</p>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card bg-light">
                    <div class="card-body text-center">
                        <h3 class="text-warning" id="overdueConfirmed">-</h3>
                        <p class="mb-0">Overdue (Time Passed)</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Setup Instructions -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0"><i class="fas fa-linux me-2"></i>Linux/Unix Setup</h5>
                    </div>
                    <div class="card-body">
                        <h6>Step 1: Open Crontab</h6>
                        <code>crontab -e</code>
                        
                        <h6 class="mt-3">Step 2: Add This Line</h6>
                        <div class="bg-dark text-light p-3 rounded">
                            <code>*/5 * * * * /usr/bin/php <?php echo __DIR__; ?>/complete_confirmed_appointments.php</code>
                        </div>
                        
                        <h6 class="mt-3">Step 3: Save and Exit</h6>
                        <p>Press <kbd>Ctrl + X</kbd>, then <kbd>Y</kbd>, then <kbd>Enter</kbd></p>
                        
                        <h6 class="mt-3">Step 4: Verify</h6>
                        <code>crontab -l</code>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fab fa-windows me-2"></i>Windows Setup</h5>
                    </div>
                    <div class="card-body">
                        <h6>Step 1: Open Task Scheduler</h6>
                        <p>Search "Task Scheduler" in Start Menu</p>
                        
                        <h6 class="mt-3">Step 2: Create Basic Task</h6>
                        <p>Right-click → "Create Basic Task"</p>
                        
                        <h6 class="mt-3">Step 3: Configure</h6>
                        <ul>
                            <li><strong>Name:</strong> Complete Confirmed Appointments</li>
                            <li><strong>Trigger:</strong> Daily, repeat every 5 minutes</li>
                            <li><strong>Action:</strong> Start a program</li>
                            <li><strong>Program:</strong> <code>php.exe</code></li>
                            <li><strong>Arguments:</strong> <code><?php echo __DIR__; ?>/complete_confirmed_appointments.php</code></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Manual Testing -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-vial me-2"></i>Manual Testing</h5>
            </div>
            <div class="card-body">
                <p>Before setting up the cron job, test it manually:</p>
                
                <div class="d-grid gap-2 d-md-flex">
                    <button class="btn btn-success" onclick="runCompleteCronJob()">
                        <i class="fas fa-play me-2"></i>Run Complete Cron Job Now
                    </button>
                    <button class="btn btn-info" onclick="refreshCompleteStats()">
                        <i class="fas fa-refresh me-2"></i>Refresh Statistics
                    </button>
                    <a href="complete_confirmed_appointments.php" class="btn btn-secondary" target="_blank">
                        <i class="fas fa-external-link-alt me-2"></i>Open Cron Script
                    </a>
                </div>
                
                <div id="completeResult" class="mt-3"></div>
            </div>
        </div>
        
        <!-- Log File -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-file-alt me-2"></i>Log File</h5>
            </div>
            <div class="card-body">
                <p>Monitor the cron job execution through the log file:</p>
                <code><?php echo __DIR__; ?>/../logs/cron_complete_appointments.log</code>
                
                <div class="mt-3">
                    <button class="btn btn-sm btn-outline-primary" onclick="viewCompleteLog()">
                        <i class="fas fa-eye me-2"></i>View Log
                    </button>
                    <button class="btn btn-sm btn-outline-danger" onclick="clearCompleteLog()">
                        <i class="fas fa-trash me-2"></i>Clear Log
                    </button>
                </div>
                
                <div id="completeLogContent" class="mt-3" style="display: none;">
                    <pre id="completeLogText" style="background: #f8f9fa; padding: 15px; border-radius: 5px; max-height: 300px; overflow-y: auto;"></pre>
                </div>
            </div>
        </div>
    </div>
    </div>
</div>

<script>
function runCronJob() {
    const resultDiv = document.getElementById('result');
    resultDiv.innerHTML = '<div class="alert alert-info"><i class="fas fa-spinner fa-spin me-2"></i>Running cron job...</div>';
    
    fetch('cancel_pending_bookings.php?run_cron=1')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                resultDiv.innerHTML = `
                    <div class="alert alert-success">
                        <h6><i class="fas fa-check-circle me-2"></i>Cron Job Completed Successfully</h6>
                        <p class="mb-0">
                            Cancelled: ${data.cancelled} appointments<br>
                            Errors: ${data.errors}<br>
                            Total found: ${data.total_found}
                        </p>
                    </div>
                `;
            } else {
                resultDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <h6><i class="fas fa-exclamation-triangle me-2"></i>Cron Job Failed</h6>
                        <p class="mb-0">${data.message}</p>
                    </div>
                `;
            }
            refreshStats();
        })
        .catch(error => {
            resultDiv.innerHTML = `
                <div class="alert alert-danger">
                    <h6><i class="fas fa-exclamation-triangle me-2"></i>Error</h6>
                    <p class="mb-0">Failed to run cron job: ${error.message}</p>
                </div>
            `;
        });
}

function refreshStats() {
    fetch('cancel_pending_bookings.php?get_stats=1')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('totalPending').textContent = data.stats.total_pending;
                document.getElementById('oldPending').textContent = data.stats.old_pending;
            }
        })
        .catch(error => {
            console.error('Error fetching stats:', error);
        });
}

function viewLog() {
    const logContent = document.getElementById('logContent');
    const logText = document.getElementById('logText');
    
    if (logContent.style.display === 'none') {
        // Fetch log content
        fetch('?action=view_log')
            .then(response => response.text())
            .then(data => {
                logText.textContent = data;
                logContent.style.display = 'block';
            })
            .catch(error => {
                logText.textContent = 'Error loading log: ' + error.message;
                logContent.style.display = 'block';
            });
    } else {
        logContent.style.display = 'none';
    }
}

function clearLog() {
    if (confirm('Are you sure you want to clear the log file?')) {
        fetch('?action=clear_log')
            .then(response => response.text())
            .then(data => {
                alert('Log cleared successfully');
                document.getElementById('logContent').style.display = 'none';
            })
            .catch(error => {
                alert('Error clearing log: ' + error.message);
            });
    }
}

// Complete Confirmed Appointments functions
function runCompleteCronJob() {
    const resultDiv = document.getElementById('completeResult');
    resultDiv.innerHTML = '<div class="alert alert-info"><i class="fas fa-spinner fa-spin me-2"></i>Running cron job...</div>';
    
    fetch('complete_confirmed_appointments.php?run_cron=1')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                resultDiv.innerHTML = `
                    <div class="alert alert-success">
                        <h6><i class="fas fa-check-circle me-2"></i>Cron Job Completed Successfully</h6>
                        <p class="mb-0">
                            Completed: ${data.completed} appointments<br>
                            Skipped: ${data.skipped} appointments<br>
                            Errors: ${data.errors}<br>
                            Total found: ${data.total_found}
                        </p>
                    </div>
                `;
            } else {
                resultDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <h6><i class="fas fa-exclamation-triangle me-2"></i>Cron Job Failed</h6>
                        <p class="mb-0">${data.message}</p>
                    </div>
                `;
            }
            refreshCompleteStats();
        })
        .catch(error => {
            resultDiv.innerHTML = `
                <div class="alert alert-danger">
                    <h6><i class="fas fa-exclamation-triangle me-2"></i>Error</h6>
                    <p class="mb-0">Failed to run cron job: ${error.message}</p>
                </div>
            `;
        });
}

function refreshCompleteStats() {
    fetch('complete_confirmed_appointments.php?get_stats=1')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('totalConfirmed').textContent = data.stats.total_confirmed;
                document.getElementById('overdueConfirmed').textContent = data.stats.overdue;
            }
        })
        .catch(error => {
            console.error('Error fetching stats:', error);
        });
}

function viewCompleteLog() {
    const logContent = document.getElementById('completeLogContent');
    const logText = document.getElementById('completeLogText');
    
    if (logContent.style.display === 'none') {
        fetch('?action=view_complete_log')
            .then(response => response.text())
            .then(data => {
                logText.textContent = data;
                logContent.style.display = 'block';
            })
            .catch(error => {
                logText.textContent = 'Error loading log: ' + error.message;
                logContent.style.display = 'block';
            });
    } else {
        logContent.style.display = 'none';
    }
}

function clearCompleteLog() {
    if (confirm('Are you sure you want to clear the log file?')) {
        fetch('?action=clear_complete_log')
            .then(response => response.text())
            .then(data => {
                alert('Log cleared successfully');
                document.getElementById('completeLogContent').style.display = 'none';
            })
            .catch(error => {
                alert('Error clearing log: ' + error.message);
            });
    }
}

// Load stats on page load
document.addEventListener('DOMContentLoaded', function() {
    refreshStats();
    refreshCompleteStats();
});
</script>

<?php
// Handle log actions
if (isset($_GET['action'])) {
    if ($_GET['action'] === 'view_log') {
        $logFile = '../logs/cron_cancel_bookings.log';
        if (file_exists($logFile)) {
            echo file_get_contents($logFile);
        } else {
            echo 'Log file does not exist yet.';
        }
        exit;
    } elseif ($_GET['action'] === 'clear_log') {
        $logFile = '../logs/cron_cancel_bookings.log';
        if (file_exists($logFile)) {
            file_put_contents($logFile, '');
            echo 'Log cleared successfully';
        } else {
            echo 'Log file does not exist';
        }
        exit;
    } elseif ($_GET['action'] === 'view_complete_log') {
        $logFile = '../logs/cron_complete_appointments.log';
        if (file_exists($logFile)) {
            echo file_get_contents($logFile);
        } else {
            echo 'Log file does not exist yet.';
        }
        exit;
    } elseif ($_GET['action'] === 'clear_complete_log') {
        $logFile = '../logs/cron_complete_appointments.log';
        if (file_exists($logFile)) {
            file_put_contents($logFile, '');
            echo 'Log cleared successfully';
        } else {
            echo 'Log file does not exist';
        }
        exit;
    }
}

$content = ob_get_clean();

// Simple standalone layout
echo "<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>$page_title</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css' rel='stylesheet'>
    <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css' rel='stylesheet'>
    <style>
        body { background: #f8f9fa; }
        .content-card { background: white; border-radius: 10px; padding: 30px; margin: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .btn { margin: 5px; }
    </style>
</head>
<body>
    <div class='container-fluid'>
        <div class='row'>
            <div class='col-12'>
                $content
            </div>
        </div>
    </div>
    <script src='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js'></script>
</body>
</html>";
?>
