<?php
include 'includes/auth.php';
requireLogin();
include '../config/database.php';

if (!isAdmin()) {
    header('Location: ../dashboard.php');
    exit();
}

$page_title = "Setup Cron Job";

function setupCronJob() {
    $results = [];
    
    // Get the absolute path to the daily_reminders.php file
    $script_path = realpath(__DIR__ . '/../cron/daily_reminders.php');
    $results['script_path'] = $script_path;
    
    if (!$script_path) {
        $results['error'] = "Could not find daily_reminders.php file";
        return $results;
    }
    
    // Find PHP executable path
    $php_path = findPHPExecutable();
    $results['php_path'] = $php_path;
    
    if (!$php_path) {
        $results['error'] = "Could not find PHP executable";
        return $results;
    }
    
    // Build the cron command
    $cron_command = "0 8 * * * {$php_path} {$script_path} > /dev/null 2>&1";
    $results['cron_command'] = $cron_command;
    
    // Method 1: Try direct crontab command
    $results = tryCrontabMethod($cron_command, $results);
    
    // If Method 1 failed, provide manual instructions
    if (!isset($results['success'])) {
        $results['manual_instructions'] = generateManualInstructions($cron_command);
    }
    
    return $results;
}

function findPHPExecutable() {
    // Try different methods to find PHP path
    $possible_paths = [
        '/usr/bin/php',
        '/usr/local/bin/php',
        '/opt/plesk/php/8.2/bin/php', // Plesk common path
        '/opt/cpanel/ea-php82/root/usr/bin/php', // cPanel common path
        trim(shell_exec('which php 2>/dev/null')),
        trim(shell_exec('command -v php 2>/dev/null'))
    ];
    
    foreach ($possible_paths as $path) {
        if ($path && file_exists($path)) {
            // Test if PHP works
            $test = shell_exec("{$path} -v 2>/dev/null");
            if (strpos($test, 'PHP') !== false) {
                return $path;
            }
        }
    }
    
    return false;
}

function tryCrontabMethod($cron_command, $results) {
    // Get current crontab
    $current_crontab = shell_exec('crontab -l 2>/dev/null');
    
    // Check if cron job already exists
    if (strpos($current_crontab, 'daily_reminders.php') !== false) {
        $results['info'] = "Cron job already exists. Updated with current command.";
        
        // Remove existing entry
        $lines = explode("\n", $current_crontab);
        $new_lines = [];
        foreach ($lines as $line) {
            if (strpos($line, 'daily_reminders.php') === false) {
                $new_lines[] = $line;
            }
        }
        $new_crontab = implode("\n", $new_lines) . "\n" . $cron_command . "\n";
    } else {
        $new_crontab = $current_crontab . $cron_command . "\n";
    }
    
    // Create temporary file
    $temp_file = tempnam(sys_get_temp_dir(), 'cron_');
    file_put_contents($temp_file, $new_crontab);
    
    // Install new crontab
    $output = shell_exec("crontab {$temp_file} 2>&1");
    $return_code = 0;
    
    // Check if successful
    if (file_exists($temp_file)) {
        unlink($temp_file);
    }
    
    // Verify the cron job was added
    $verify_crontab = shell_exec('crontab -l 2>/dev/null');
    if (strpos($verify_crontab, 'daily_reminders.php') !== false) {
        $results['success'] = "Cron job successfully installed!";
        $results['current_crontab'] = $verify_crontab;
    } else {
        $results['warning'] = "Could not automatically install cron job. Please use manual method below.";
    }
    
    return $results;
}

function generateManualInstructions($cron_command) {
    $instructions = "
    <h4>Manual Setup Instructions:</h4>
    <ol>
        <li><strong>Connect to your server via SSH</strong></li>
        <li><strong>Run this command to edit crontab:</strong>
            <code>crontab -e</code>
        </li>
        <li><strong>Add this line to the file:</strong>
            <div class='code-block'>{$cron_command}</div>
        </li>
        <li><strong>Save and exit:</strong>
            <ul>
                <li>For <strong>nano</strong>: Press <code>Ctrl+X</code>, then <code>Y</code>, then <code>Enter</code></li>
                <li>For <strong>vim</strong>: Press <code>Esc</code>, type <code>:wq</code>, then <code>Enter</code></li>
            </ul>
        </li>
        <li><strong>Verify the cron job was added:</strong>
            <code>crontab -l</code>
        </li>
    </ol>";
    
    return $instructions;
}

function testCronExecution() {
    $script_path = realpath(__DIR__ . '/../cron/daily_reminders.php');
    $php_path = findPHPExecutable();
    
    if (!$script_path || !$php_path) {
        return "Cannot test - missing paths";
    }
    
    $command = "{$php_path} {$script_path}";
    $output = shell_exec("{$command} 2>&1");
    
    return $output ?: "No output received";
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['setup_cron'])) {
        $results = setupCronJob();
    } elseif (isset($_POST['test_cron'])) {
        $test_results = testCronExecution();
    }
}

include 'includes/header.php';
?>

<div class="dashboard">
    <div class="dashboard-header">
        <h1>Setup Automatic Reminders</h1>
        <p>Configure daily email reminders for birthdays and anniversaries</p>
    </div>

    <?php if (isset($results['success'])): ?>
        <div class="alert success">
            <i class="fas fa-check-circle"></i>
            <?php echo $results['success']; ?>
        </div>
    <?php endif; ?>

    <?php if (isset($results['error'])): ?>
        <div class="alert error">
            <i class="fas fa-exclamation-circle"></i>
            <?php echo $results['error']; ?>
        </div>
    <?php endif; ?>

    <?php if (isset($results['warning'])): ?>
        <div class="alert warning">
            <i class="fas fa-exclamation-triangle"></i>
            <?php echo $results['warning']; ?>
        </div>
    <?php endif; ?>

    <?php if (isset($results['info'])): ?>
        <div class="alert info">
            <i class="fas fa-info-circle"></i>
            <?php echo $results['info']; ?>
        </div>
    <?php endif; ?>

    <div class="dashboard-content">
        <div class="dashboard-card">
            <div class="card-header">
                <h2><i class="fas fa-cog"></i> Automatic Cron Setup</h2>
            </div>
            <div class="card-body">
                <div class="system-info">
                    <h3>System Information</h3>
                    <div class="info-grid">
                        <div class="info-item">
                            <label>PHP Executable:</label>
                            <span><?php echo isset($results['php_path']) ? $results['php_path'] : findPHPExecutable() ?: 'Not found'; ?></span>
                        </div>
                        <div class="info-item">
                            <label>Script Path:</label>
                            <span><?php echo realpath(__DIR__ . '/../cron/daily_reminders.php') ?: 'Not found'; ?></span>
                        </div>
                        <div class="info-item">
                            <label>Cron Command:</label>
                            <span class="code"><?php echo isset($results['cron_command']) ? $results['cron_command'] : 'Run setup to generate'; ?></span>
                        </div>
                    </div>
                </div>

                <div class="setup-actions">
                    <form method="POST" class="inline-form">
                        <button type="submit" name="setup_cron" class="btn btn-gold">
                            <i class="fas fa-magic"></i>
                            Auto-Setup Cron Job
                        </button>
                    </form>

                    <form method="POST" class="inline-form">
                        <button type="submit" name="test_cron" class="btn btn-secondary">
                            <i class="fas fa-play"></i>
                            Test Reminder Script
                        </button>
                    </form>
                </div>

                <?php if (isset($test_results)): ?>
                    <div class="test-results">
                        <h4>Test Results:</h4>
                        <pre><?php echo htmlspecialchars($test_results); ?></pre>
                    </div>
                <?php endif; ?>

                <?php if (isset($results['current_crontab'])): ?>
                    <div class="current-crontab">
                        <h4>Current Crontab:</h4>
                        <pre><?php echo htmlspecialchars($results['current_crontab']); ?></pre>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php if (isset($results['manual_instructions'])): ?>
        <div class="dashboard-card">
            <div class="card-header">
                <h2><i class="fas fa-terminal"></i> Manual Setup Required</h2>
            </div>
            <div class="card-body">
                <?php echo $results['manual_instructions']; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="dashboard-card">
            <div class="card-header">
                <h2><i class="fas fa-info-circle"></i> About Automatic Reminders</h2>
            </div>
            <div class="card-body">
                <div class="reminder-info">
                    <h3>What this does:</h3>
                    <ul>
                        <li>✅ Runs daily at 8:00 AM</li>
                        <li>✅ Checks for birthdays and anniversaries happening today</li>
                        <li>✅ Sends formatted email reminders to the specified address</li>
                        <li>✅ Works automatically in the background</li>
                    </ul>
                    
                    <h3>Email Configuration:</h3>
                    <p>Make sure to configure your email settings in <code>config/email_config.php</code></p>
                    
                    <div class="alert info">
                        <i class="fas fa-envelope"></i>
                        Reminders will be sent to: <strong><?php 
                        @include '../config/email_config.php';
                        echo defined('REMINDER_RECIPIENT_EMAIL') ? REMINDER_RECIPIENT_EMAIL : 'Not configured';
                        ?></strong>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.code-block {
    background: #f4f4f4;
    border: 1px solid #ddd;
    padding: 10px;
    border-radius: 4px;
    margin: 10px 0;
    font-family: monospace;
}

.code {
    font-family: monospace;
    background: #f4f4f4;
    padding: 2px 6px;
    border-radius: 3px;
}

.info-grid {
    display: grid;
    grid-template-columns: 1fr 2fr;
    gap: 10px;
    margin: 15px 0;
}

.info-item {
    padding: 8px 0;
    border-bottom: 1px solid #eee;
}

.info-item label {
    font-weight: bold;
    color: #555;
}

.setup-actions {
    margin: 20px 0;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.inline-form {
    display: inline;
}

.test-results, .current-crontab {
    margin-top: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 4px;
}

.test-results pre, .current-crontab pre {
    white-space: pre-wrap;
    word-wrap: break-word;
}

.reminder-info ul {
    list-style: none;
    padding-left: 0;
}

.reminder-info li {
    padding: 5px 0;
}

.reminder-info li:before {
    content: "• ";
    color: #28a745;
    font-weight: bold;
}
</style>

<?php include 'includes/footer.php'; ?>