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

echo "<h2>Notification System Debug - " . SITE_NAME . "</h2>";

$database = new Database();
$db = $database->getConnection();

try {
    echo "<h3>1. Checking Database Tables:</h3>";
    
    // Check if notifications table exists
    $stmt = $db->query("SHOW TABLES LIKE 'notifications'");
    if ($stmt->rowCount() > 0) {
        echo "✓ notifications table exists<br>";
        
        // Check table structure
        $stmt = $db->query("DESCRIBE notifications");
        $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
        echo "Table columns: " . implode(', ', $columns) . "<br>";
    } else {
        echo "✗ notifications table missing - creating it...<br>";
        
        $sql = "
        CREATE TABLE notifications (
            id INT PRIMARY KEY AUTO_INCREMENT,
            user_type ENUM('candidate', 'company', 'admin') NOT NULL,
            user_id INT NOT NULL,
            title VARCHAR(255) NOT NULL,
            message TEXT NOT NULL,
            type ENUM('info', 'success', 'warning', 'error') DEFAULT 'info',
            related_type ENUM('application', 'job', 'interview', 'general') DEFAULT 'general',
            related_id INT NULL,
            is_read BOOLEAN DEFAULT FALSE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_user_notifications (user_type, user_id, is_read),
            INDEX idx_created_at (created_at)
        )";
        
        $db->exec($sql);
        echo "✓ notifications table created<br>";
    }
    
    // Check if email_notifications table exists
    $stmt = $db->query("SHOW TABLES LIKE 'email_notifications'");
    if ($stmt->rowCount() > 0) {
        echo "✓ email_notifications table exists<br>";
    } else {
        echo "✗ email_notifications table missing - creating it...<br>";
        
        $sql = "
        CREATE TABLE email_notifications (
            id INT PRIMARY KEY AUTO_INCREMENT,
            to_email VARCHAR(255) NOT NULL,
            subject VARCHAR(255) NOT NULL,
            message TEXT NOT NULL,
            status ENUM('pending', 'sent', 'failed') DEFAULT 'pending',
            sent_at TIMESTAMP NULL,
            error_message TEXT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_status (status),
            INDEX idx_created_at (created_at)
        )";
        
        $db->exec($sql);
        echo "✓ email_notifications table created<br>";
    }
    
    echo "<h3>2. Testing Application Status Change Flow:</h3>";
    
    // Get a test application
    $stmt = $db->query("
        SELECT ja.*, c.email, c.first_name, c.last_name, j.title as job_title, comp.name as company_name
        FROM job_applications ja
        JOIN candidates c ON ja.candidate_id = c.id
        JOIN jobs j ON ja.job_id = j.id
        JOIN companies comp ON j.company_id = comp.id
        LIMIT 1
    ");
    $test_application = $stmt->fetch();
    
    if ($test_application) {
        echo "✓ Found test application - ID: " . $test_application['id'] . "<br>";
        echo "Candidate: " . htmlspecialchars($test_application['first_name'] . ' ' . $test_application['last_name']) . "<br>";
        echo "Email: " . htmlspecialchars($test_application['email']) . "<br>";
        echo "Job: " . htmlspecialchars($test_application['job_title']) . "<br>";
        echo "Current Status: " . $test_application['status'] . "<br>";
        
        echo "<h3>3. Testing Notification System:</h3>";
        
        require_once 'includes/notification_system.php';
        $notificationSystem = new NotificationSystem($db);
        
        // Test creating in-app notification
        $result = $notificationSystem->createNotification(
            'candidate',
            $test_application['candidate_id'],
            'Test Notification',
            'This is a test notification to verify the system is working.',
            'info',
            'application',
            $test_application['id']
        );
        
        if ($result) {
            echo "✓ In-app notification created successfully<br>";
        } else {
            echo "✗ Failed to create in-app notification<br>";
        }
        
        echo "<h3>4. Testing Email Service:</h3>";
        
        require_once 'includes/email_service.php';
        $emailService = new EmailService($db);
        
        // Test simple email
        $test_email = $test_application['email'];
        echo "Sending test email to: $test_email<br>";
        
        $email_result = $emailService->testEmail($test_email);
        
        if ($email_result) {
            echo "✓ Test email sent successfully<br>";
        } else {
            echo "✗ Test email failed<br>";
        }
        
        echo "<h3>5. Testing Full Notification Flow:</h3>";
        
        $notification_result = $notificationSystem->notifyApplicationStatusChange(
            $test_application['id'],
            $test_application['status'],
            'shortlisted' // Test status
        );
        
        if ($notification_result) {
            echo "✓ Full notification flow completed successfully<br>";
        } else {
            echo "✗ Full notification flow failed<br>";
        }
        
    } else {
        echo "✗ No test applications found in database<br>";
        echo "Please create some job applications first to test notifications<br>";
    }
    
    echo "<h3>6. Checking Email Log:</h3>";
    
    $stmt = $db->query("SELECT * FROM email_notifications ORDER BY created_at DESC LIMIT 10");
    $emails = $stmt->fetchAll();
    
    if (empty($emails)) {
        echo "No emails in log<br>";
    } else {
        echo "<table border='1' style='width:100%; border-collapse: collapse;'>";
        echo "<tr style='background:#f0f0f0;'><th>ID</th><th>To</th><th>Subject</th><th>Status</th><th>Created</th><th>Error</th></tr>";
        foreach ($emails as $email) {
            $status_color = $email['status'] === 'sent' ? 'green' : ($email['status'] === 'failed' ? 'red' : 'orange');
            echo "<tr>";
            echo "<td>" . $email['id'] . "</td>";
            echo "<td>" . htmlspecialchars($email['to_email']) . "</td>";
            echo "<td>" . htmlspecialchars(substr($email['subject'], 0, 40)) . "...</td>";
            echo "<td style='color:$status_color; font-weight:bold;'>" . $email['status'] . "</td>";
            echo "<td>" . $email['created_at'] . "</td>";
            echo "<td>" . htmlspecialchars($email['error_message'] ?? '') . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    
    echo "<h3>7. PHP Email Configuration:</h3>";
    echo "SMTP: " . ini_get('SMTP') . "<br>";
    echo "smtp_port: " . ini_get('smtp_port') . "<br>";
    echo "sendmail_from: " . ini_get('sendmail_from') . "<br>";
    
    echo "<h3>8. Recommendations:</h3>";
    echo "<div style='background:#fff3cd; border:1px solid #ffeaa7; padding:15px; border-radius:5px;'>";
    echo "<strong>If emails are still not working:</strong><br>";
    echo "1. Check the email log above for error messages<br>";
    echo "2. Configure SMTP in config/email_config.php (copy from .example)<br>";
    echo "3. For Gmail: Enable 2-factor auth and use App Password<br>";
    echo "4. Test with a real email service like SendGrid or Mailgun<br>";
    echo "5. Check server firewall settings<br>";
    echo "</div>";
    
} catch (Exception $e) {
    echo "<div style='color:red; background:#ffebee; padding:15px; border-radius:5px;'>";
    echo "<strong>Error:</strong> " . htmlspecialchars($e->getMessage()) . "<br>";
    echo "<strong>File:</strong> " . $e->getFile() . "<br>";
    echo "<strong>Line:</strong> " . $e->getLine() . "<br>";
    echo "</div>";
}
?>

<style>
body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
table { border-collapse: collapse; margin: 10px 0; width: 100%; }
th, td { padding: 8px; text-align: left; border: 1px solid #ddd; }
th { background-color: #f2f2f2; font-weight: bold; }
h3 { color: #0066cc; border-bottom: 2px solid #0066cc; padding-bottom: 5px; }
</style>