<?php
/**
 * Quick test of the API after session fix
 */

// Simulate admin session
session_start();
$_SESSION['user_id'] = 1;
$_SESSION['user_name'] = 'Test Admin';
$_SESSION['user_email'] = 'admin@test.com';
$_SESSION['user_role'] = 'admin';

echo "=== Test Admin Session ===\n\n";
echo "Session Set:\n";
echo "  user_id: " . $_SESSION['user_id'] . "\n";
echo "  user_role: " . $_SESSION['user_role'] . "\n";
echo "  user_email: " . $_SESSION['user_email'] . "\n\n";

// Check if authorized
$isLoggedIn = !empty($_SESSION['user_id']);
$isAdmin = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';

echo "Authorization Check:\n";
echo "  isLoggedIn: " . ($isLoggedIn ? "TRUE" : "FALSE") . "\n";
echo "  isAdmin: " . ($isAdmin ? "TRUE" : "FALSE") . "\n";
echo "  Can access API: " . (($isLoggedIn && $isAdmin) ? "YES ✅" : "NO ❌") . "\n\n";

// Now simulate the API call
require_once 'config/config.php';
require_once 'classes/Database.php';

$_POST['test_email'] = 'ssandy8435@gmail.com';
$_SERVER['REQUEST_METHOD'] = 'POST';

echo "=== Simulating API Call ===\n\n";

header('Content-Type: application/json');

$db = Database::getInstance();

// Get email settings
$settings = [];
$keys = ['mail_host', 'mail_port', 'mail_encryption', 'mail_username', 'mail_from_email', 'mail_from_name'];

foreach ($keys as $key) {
    $setting = $db->fetch('SELECT setting_value FROM admin_settings WHERE setting_key = ?', [$key]);
    if ($setting) {
        $settings[$key] = $setting['setting_value'];
    }
}

$passwordSetting = $db->fetch('SELECT setting_value FROM admin_settings WHERE setting_key = ?', ['mail_password_encrypted']);
$password = !empty($passwordSetting['setting_value']) ? base64_decode($passwordSetting['setting_value']) : '';

echo "Email Configuration:\n";
echo "  Host: " . ($settings['mail_host'] ?? 'NOT SET') . "\n";
echo "  Port: " . ($settings['mail_port'] ?? 'NOT SET') . "\n";
echo "  User: " . (isset($settings['mail_username']) ? substr($settings['mail_username'], 0, 5) . "***" : "NOT SET") . "\n";
echo "  From: " . ($settings['mail_from_email'] ?? 'NOT SET') . "\n";
echo "  Password: " . (empty($password) ? "NOT SET" : "[ENCRYPTED]") . "\n\n";

if (!empty($settings['mail_host']) && !empty($settings['mail_username']) && !empty($password)) {
    echo "✅ Configuration is complete\n";
    echo "✅ API call would succeed\n";
} else {
    echo "❌ Configuration incomplete\n";
}

?>
