<?php
// backend/test_admin_api.php
require_once 'config/cors.php';
require_once 'config/database.php';
require_once 'utils/helpers.php';

// Mock functionality
echo "Testing Admin API...\n";

try {
    // 1. Create a dummy admin user if not exists
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = 'admin@example.com'");
    $stmt->execute();
    $user = $stmt->fetch();

    if (!$user) {
        echo "Creating test admin user...\n";
        // Use environment variable or generate random password for testing
        $testPassword = getenv('TEST_ADMIN_PASSWORD') ?: bin2hex(random_bytes(8));
        $passwordHash = password_hash($testPassword, PASSWORD_BCRYPT);
        $userId = generateUUID(); // Use UUID
        $stmt = $pdo->prepare("INSERT INTO users (id, email, password_hash, first_name, last_name, is_approved, email_verified) VALUES (?, 'admin@example.com', ?, 'Admin', 'User', 1, 1)");
        $stmt->execute([$userId, $passwordHash]);
        echo "Test admin password: $testPassword (set TEST_ADMIN_PASSWORD env var to use custom password)\n";
    } else {
        $userId = $user['id'];
    }

    echo "Admin User ID: $userId\n";

    // Ensure Admin Role exists
    echo "Checking roles...\n";
    $stmt = $pdo->query("SELECT id FROM user_roles WHERE name = 'admin' OR name = 'Admin'");
    $role = $stmt->fetch();
    if (!$role) {
        echo "Creating admin role...\n";
        $stmt = $pdo->prepare("INSERT INTO user_roles (name) VALUES ('admin')");
        $stmt->execute();
        $roleId = $pdo->lastInsertId();
    } else {
        $roleId = $role['id'];
    }

    // Ensure Profile exists
    $stmt = $pdo->prepare("SELECT id FROM profiles WHERE user_id = ?");
    $stmt->execute([$userId]);
    $profile = $stmt->fetch();

    if (!$profile) {
        echo "Creating admin profile...\n";
        $profileId = generateUUID();
        $stmt = $pdo->prepare("INSERT INTO profiles (id, user_id, first_name, last_name, role_id) VALUES (?, ?, 'Admin', 'User', ?)");
        $stmt->execute([$profileId, $userId, $roleId]);
    } else {
        // Update role to admin
        $stmt = $pdo->prepare("UPDATE profiles SET role_id = ? WHERE user_id = ?");
        $stmt->execute([$roleId, $userId]);
    }

    echo "Admin Profile configured.\n";

    // 2. Create a session/token
    $sessionId = generateUUID();
    $token = bin2hex(random_bytes(32));
    $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
    
    $stmt = $pdo->prepare("INSERT INTO sessions (id, user_id, session_token, expires_at) VALUES (?, ?, ?, ?)");
    $stmt->execute([$sessionId, $userId, $token, $expires]);

    echo "Generated Token: $token\n";

    // 3. Simulate Request to admin-dashboard.php logic
    // We can't include admin-dashboard.php directly because it outputs JSON and exits.
    // Instead we will replicate the checks.

    $detectedUser = getUserFromToken($token);
    if ($detectedUser) {
        echo "User authenticated via token: " . $detectedUser['email'] . "\n";
    } else {
        echo "FAILED: User not found via token.\n";
        exit(1);
    }

    if (isAdmin($detectedUser['id'])) {
        echo "User is Admin.\n";
    } else {
        echo "FAILED: User is NOT Admin.\n";
        exit(1);
    }

    echo "Auth checks passed. Running curl against running server...\n";
    
    // 4. Curl the actual endpoint
    $ch = curl_init('http://localhost:8080/api/admin-dashboard.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json'
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    echo "Response Code: $httpCode\n";
    echo "Response Data: " . substr($response, 0, 500) . "...\n";

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
