<?php
// Test Script to debug Auth Loop
// Run with: php test_auth_loop.php

echo "1. Registering User...\n";
$url = 'http://localhost:8086/server/auth.php';
$regData = json_encode([
    'action' => 'register',
    'email' => 'looptest@test.com',
    'username' => 'looptest',
    'password' => 'pass123',
    'whatsapp' => '00000'
]);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $regData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($ch);
echo "Response: " . $response . "\n";
curl_close($ch);

// parse verify token? No, we need to inspect users.json because email is mocked
// ... but wait, the register returns success: true.
// The browser got a verify modal.

echo "\n2. Verifying User (Mock Token)...\n";
// Actually, I need to read the token from users.json to verify it properly
$users = json_decode(file_get_contents('c:\Users\kunzl\OneDrive\Documents\Ghadget\server\data\users.json'), true);
$token = null;
foreach ($users as $u) {
    if ($u['email'] === 'looptest@test.com') {
        $token = $u['verify_token'];
        break;
    }
}

if (!$token) {
    echo "CRITICAL: verify_token not found for looptest@test.com\n";
    exit;
}

echo "Found Token: $token\n";

// Verify with OTP 
// Wait, the client used `token: otp` (where otp was 000000). 
// The server script expects `action: verify_token` with `token: ...magic_token...`. 
// BUT the client script I wrote sends `action: verify_otp` with `token: otp_value` and `email`.
// CHECK AUTH.PHP AGAIN. Does it handle `verify_otp` action?

$verifyData = json_encode([
    'action' => 'verify_otp', // This is what the client sends!
    'email' => 'looptest@test.com',
    'token' => '123456'
]);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $verifyData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$respVerify = curl_exec($ch);
echo "Verify Response: " . $respVerify . "\n";
curl_close($ch);
