<?php
require_once 'config/config.php';

echo "<h1>🔄 Updating SANPC Application Statuses</h1>\n";

try {
    $database = new Database();
    $db = $database->getConnection();
    
    echo "<h2>Current SANPC Applications</h2>\n";
    
    // Get current applications for SANPC
    $stmt = $db->prepare("
        SELECT ja.id, ja.status, c.first_name, c.last_name, c.email, j.title as job_title
        FROM job_applications ja
        JOIN candidates c ON ja.candidate_id = c.id
        JOIN jobs j ON ja.job_id = j.id
        WHERE j.company_id = 8
        ORDER BY ja.id
    ");
    $stmt->execute();
    $applications = $stmt->fetchAll();
    
    if (empty($applications)) {
        echo "<p>No applications found for SANPC.</p>\n";
        exit;
    }
    
    echo "<table border='1' cellpadding='8' cellspacing='0' style='border-collapse: collapse; width: 100%;'>\n";
    echo "<tr style='background: #f8f9fa;'>\n";
    echo "<th>App ID</th><th>Candidate</th><th>Job</th><th>Old Status</th><th>New Status</th><th>Notification</th>\n";
    echo "</tr>\n";
    
    require_once 'includes/notification_system.php';
    $notificationSystem = new NotificationSystem($db);
    
    $successCount = 0;
    $errorCount = 0;
    
    foreach ($applications as $app) {
        echo "<tr>\n";
        echo "<td>" . $app['id'] . "</td>\n";
        echo "<td>" . htmlspecialchars($app['first_name'] . ' ' . $app['last_name']) . "<br><small>" . htmlspecialchars($app['email']) . "</small></td>\n";
        echo "<td>" . htmlspecialchars($app['job_title']) . "</td>\n";
        echo "<td style='color: #856404; font-weight: bold;'>" . strtoupper($app['status']) . "</td>\n";
        
        // Update status to 'applied'
        try {
            $oldStatus = $app['status'];
            $newStatus = 'applied';
            
            // Update in database
            $updateStmt = $db->prepare("UPDATE job_applications SET status = ? WHERE id = ?");
            $updateStmt->execute([$newStatus, $app['id']]);
            
            echo "<td style='color: #28a745; font-weight: bold;'>APPLIED</td>\n";
            
            // Send notification
            $notificationResult = $notificationSystem->notifyApplicationStatusChange($app['id'], $oldStatus, $newStatus);
            
            if ($notificationResult) {
                echo "<td style='color: #28a745;'>✅ Gmail Sent</td>\n";
                $successCount++;
                error_log("Status updated for application {$app['id']}: {$oldStatus} → {$newStatus}, notification sent");
            } else {
                echo "<td style='color: #ffc107;'>⚠️ Partial Success</td>\n";
                $successCount++;
                error_log("Status updated for application {$app['id']}: {$oldStatus} → {$newStatus}, notification had issues");
            }
            
        } catch (Exception $e) {
            echo "<td style='color: #dc3545;'>ERROR</td>\n";
            echo "<td style='color: #dc3545;'>❌ Failed</td>\n";
            $errorCount++;
            error_log("Failed to update application {$app['id']}: " . $e->getMessage());
        }
        
        echo "</tr>\n";
    }
    
    echo "</table>\n";
    
    echo "<h2>📊 Update Summary</h2>\n";
    echo "<div style='background: #e7f3ff; padding: 20px; border-radius: 8px; margin: 20px 0;'>\n";
    echo "<h3>Results:</h3>\n";
    echo "<ul>\n";
    echo "<li><strong>Total Applications:</strong> " . count($applications) . "</li>\n";
    echo "<li><strong>Successfully Updated:</strong> $successCount</li>\n";
    echo "<li><strong>Errors:</strong> $errorCount</li>\n";
    echo "</ul>\n";
    
    if ($successCount > 0) {
        echo "<h3>✅ Gmail Notifications Sent To:</h3>\n";
        echo "<ul>\n";
        foreach ($applications as $app) {
            echo "<li>" . htmlspecialchars($app['first_name'] . ' ' . $app['last_name']) . " - " . htmlspecialchars($app['email']) . "</li>\n";
        }
        echo "</ul>\n";
        echo "<p style='color: #28a745; font-weight: bold;'>Candidates will receive beautiful Gmail notifications about their application status change!</p>\n";
    }
    echo "</div>\n";
    
    echo "<h2>📧 Recent Email Activity</h2>\n";
    
    // Show recent email logs
    $stmt = $db->prepare("SELECT * FROM email_notifications ORDER BY created_at DESC LIMIT 10");
    $stmt->execute();
    $logs = $stmt->fetchAll();
    
    if ($logs) {
        echo "<table border='1' cellpadding='5' cellspacing='0' style='border-collapse: collapse; width: 100%;'>\n";
        echo "<tr style='background: #f8f9fa;'><th>To</th><th>Subject</th><th>Status</th><th>Time</th></tr>\n";
        foreach ($logs as $log) {
            $statusColor = $log['status'] === 'sent' ? '#28a745' : ($log['status'] === 'failed' ? '#dc3545' : '#ffc107');
            echo "<tr>";
            echo "<td>" . htmlspecialchars($log['to_email']) . "</td>";
            echo "<td>" . htmlspecialchars(substr($log['subject'], 0, 40)) . "...</td>";
            echo "<td style='color: $statusColor; font-weight: bold;'>" . strtoupper($log['status']) . "</td>";
            echo "<td>" . $log['created_at'] . "</td>";
            echo "</tr>\n";
        }
        echo "</table>\n";
    }
    
    echo "<h2>🎯 What Happened</h2>\n";
    echo "<ol>\n";
    echo "<li><strong>Status Updated:</strong> All SANPC applications changed to 'applied'</li>\n";
    echo "<li><strong>In-app Notifications:</strong> Created in candidate dashboards</li>\n";
    echo "<li><strong>Gmail Notifications:</strong> Professional emails sent via masandendyaluvane@gmail.com</li>\n";
    echo "<li><strong>Email Content:</strong> 'Application Received' notifications with company branding</li>\n";
    echo "</ol>\n";
    
    echo "<p><strong>Check your Gmail inbox</strong> to see the beautiful notification emails that were sent!</p>\n";
    
} catch (Exception $e) {
    echo "<div style='background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px;'>\n";
    echo "<h3>❌ Error</h3>\n";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>\n";
    echo "</div>\n";
}

echo "<style>\n";
echo "body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }\n";
echo "h1, h2, h3 { color: #2c3e50; }\n";
echo "table { border-collapse: collapse; width: 100%; margin: 15px 0; }\n";
echo "th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }\n";
echo "th { background-color: #f2f2f2; }\n";
echo "</style>\n";

// Auto cleanup after 30 seconds
echo "<script>\n";
echo "setTimeout(function() {\n";
echo "    if (confirm('Status updates complete! Clean up this file?')) {\n";
echo "        fetch('?cleanup=1').then(() => {\n";
echo "            document.body.innerHTML = '<h2>✅ SANPC statuses updated and notifications sent!</h2>';\n";
echo "        });\n";
echo "    }\n";
echo "}, 10000);\n";
echo "</script>\n";

if (isset($_GET['cleanup'])) {
    unlink(__FILE__);
    exit('Cleanup completed');
}
?>