<?php
define('COOKIE_FILE', 'C:/xampp/htdocs/inveetaire/scratch/crew_test_cookies.txt');
define('BASE_URL', 'http://localhost/inveetaire');

@unlink(COOKIE_FILE);

function http(string $method, string $path, array $postData = []): array {
    $url = BASE_URL . $path;
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_COOKIEJAR      => COOKIE_FILE,
        CURLOPT_COOKIEFILE     => COOKIE_FILE,
        CURLOPT_HEADER         => true,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_USERAGENT      => 'TestAgent/1.0',
    ]);
    if (strtoupper($method) === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
    }
    $raw      = curl_exec($ch);
    $code     = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    $parts = explode("\r\n\r\n", $raw, 2);
    $body = end($parts);
    return ['code' => $code, 'body' => $body, 'url' => $finalUrl];
}

function getCsrfToken(string $html): string {
    if (preg_match('/<input[^>]+name=["\']_csrf["\'][^>]+value=["\']([^"\']+)["\']/', $html, $m)) return $m[1];
    if (preg_match('/value=["\']([a-f0-9]{32,64})["\'][^>]+name=["\']_csrf["\']/', $html, $m)) return $m[1];
    return '';
}

function getTitle(string $html): string {
    preg_match('/<title>([^<]+)<\/title>/', $html, $m);
    return $m[1] ?? 'N/A';
}

// 1. GET /couple login page
$r = http('GET', '/couple');
$csrf = getCsrfToken($r['body']);
echo "1. GET /couple: code={$r['code']} csrf=" . ($csrf ? substr($csrf, 0, 12) . '...' : 'NOT FOUND') . "\n";

// Show cookie jar after GET
$cookies = file_get_contents(COOKIE_FILE);
echo "   Cookie jar:\n";
foreach (explode("\n", $cookies) as $line) {
    if ($line && !str_starts_with($line, '#')) echo "   $line\n";
}

// 2. POST /couple login as crew
$r2 = http('POST', '/couple', [
    'identifier' => 'crew',
    'password'   => 'admin',
    '_csrf'      => $csrf,
]);
echo "2. POST /couple (crew): code={$r2['code']} url={$r2['url']}\n";
echo "   Title: " . getTitle($r2['body']) . "\n";

// Show cookie jar after login
$cookies = file_get_contents(COOKIE_FILE);
echo "   Cookie jar after login:\n";
foreach (explode("\n", $cookies) as $line) {
    if ($line && !str_starts_with($line, '#')) echo "   $line\n";
}

// 3. Check session file
preg_match('/inveetaire_session\s+([a-z0-9]+)/', $cookies, $sm);
$sessionId = $sm[1] ?? '';
echo "   Session ID: $sessionId\n";
if ($sessionId) {
    $sessFile = "C:/xampp/htdocs/inveetaire/storage/sessions/sess_$sessionId";
    if (file_exists($sessFile)) {
        echo "   Session data: " . substr(file_get_contents($sessFile), 0, 200) . "\n";
    } else {
        echo "   Session file NOT found: $sessFile\n";
    }
}

// 4. Test crew operation scanner
if (strpos($r2['url'], '/app/crew') !== false) {
    echo "\n3. GET /app/crew/operation/scanner\n";
    $r3 = http('GET', '/app/crew/operation/scanner');
    echo "   code={$r3['code']} url={$r3['url']}\n";
    echo "   Title: " . getTitle($r3['body']) . "\n";
}
