<?php

function run_test(string $name, callable $test) {
    try {
        $test();
        echo "✅ PASS: $name\n";
    } catch (\Throwable $e) {
        echo "❌ FAIL: $name\n";
        echo "   Error: " . $e->getMessage() . "\n";
    }
}

function http_get(string $url, &$cookieJar = []) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    
    $response = curl_exec($ch);
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $headers = substr($response, 0, $headerSize);
    $body = substr($response, $headerSize);
    curl_close($ch);
    
    // Extract cookie
    preg_match('/Set-Cookie:\s*([^=]+=[^;]+)/i', $headers, $cookieMatch);
    if (!empty($cookieMatch[1])) {
        $cookieJar[] = $cookieMatch[1];
    }
    
    return ['headers' => $headers, 'body' => $body];
}

function http_post(string $url, array $data, array $cookies) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    
    if (!empty($cookies)) {
        curl_setopt($ch, CURLOPT_COOKIE, implode('; ', $cookies));
    }
    
    $response = curl_exec($ch);
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $headers = substr($response, 0, $headerSize);
    $body = substr($response, $headerSize);
    curl_close($ch);
    
    return ['headers' => $headers, 'body' => $body];
}

function test_login(string $identifier, string $password) {
    $cookies = [];
    $getRes = http_get('http://localhost/inveetaire/login', $cookies);
    
    // Parse CSRF token
    preg_match('/name="_csrf"\s*value="([^"]+)"/i', $getRes['body'], $csrfMatch);
    $csrf = $csrfMatch[1] ?? '';
    
    if (empty($csrf)) {
        throw new Exception("Could not find CSRF token in GET response");
    }
    
    $postData = [
        'identifier' => $identifier,
        'password'   => $password,
        '_csrf'      => $csrf
    ];
    
    return http_post('http://localhost/inveetaire/login', $postData, $cookies);
}

run_test('Super Admin login (admin / admin)', function () {
    $res = test_login('admin', 'admin');
    if (strpos($res['headers'], 'Location: http://localhost/inveetaire/app/admin/dashboard') === false) {
        throw new Exception("Expected redirect to '/app/admin/dashboard'. Headers received:\n" . $res['headers']);
    }
});

run_test('Crew login (crew / admin)', function () {
    $res = test_login('crew', 'admin');
    if (strpos($res['headers'], 'Location: http://localhost/inveetaire/app/crew/dashboard') === false) {
        throw new Exception("Expected redirect to '/app/crew/dashboard'. Headers received:\n" . $res['headers']);
    }
});

run_test('Test Couple login (test / test123)', function () {
    $res = test_login('test', 'test123');
    if (strpos($res['headers'], 'Location: http://localhost/inveetaire/app/couple/dashboard') === false) {
        throw new Exception("Expected redirect to '/app/couple/dashboard'. Headers received:\n" . $res['headers']);
    }
});

run_test('Invalid credentials returns 302 back to login page', function () {
    $res = test_login('admin', 'wrong_password');
    if (strpos($res['headers'], 'Location: http://localhost/inveetaire/login') === false) {
        throw new Exception("Expected redirect back to '/login'. Headers received:\n" . $res['headers']);
    }
});
