<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/supabase.php';
require_once __DIR__ . '/../includes/auth.php';

$input = getInput();
$action = $input['action'] ?? '';

switch ($action) {
    case 'signup':
        handleSignup($input);
        break;
    case 'login':
        handleLogin($input);
        break;
    case 'guest':
        handleGuest();
        break;
    case 'refresh':
        handleRefresh($input);
        break;
    case 'logout':
        handleLogout();
        break;
    case 'me':
        handleMe();
        break;
    case 'delete-account':
        handleDeleteAccount($input);
        break;
    default:
        jsonError('Invalid action', 400);
}

function handleSignup(array $input): void {
    $email = trim($input['email'] ?? '');
    $password = $input['password'] ?? '';
    $username = trim($input['username'] ?? '');

    if (!$email || !$password || !$username) {
        jsonError('Email, password and username are required');
    }
    if (strlen($password) < 6) {
        jsonError('Password must be at least 6 characters');
    }
    if (strlen($username) < 3 || strlen($username) > 20) {
        jsonError('Username must be 3-20 characters');
    }

    $result = supabaseAuth('POST', 'signup', [
        'email' => $email,
        'password' => $password,
        'data' => ['username' => $username]
    ]);

    if (isset($result['error'])) {
        jsonError($result['error'], $result['code'] ?? 400);
    }

    if (isset($result['access_token'])) {
        $db = supabase($result['access_token']);
        $db->update('profiles', [
            'username' => $username,
            'display_name' => $username
        ], ['id' => 'eq.' . $result['user']['id']]);

        jsonResponse([
            'access_token' => $result['access_token'],
            'refresh_token' => $result['refresh_token'],
            'user' => $result['user']
        ]);
    }

    jsonResponse($result);
}

function handleLogin(array $input): void {
    $email = trim($input['email'] ?? '');
    $password = $input['password'] ?? '';

    if (!$email || !$password) {
        jsonError('Email and password are required');
    }

    $result = supabaseAuth('POST', 'token?grant_type=password', [
        'email' => $email,
        'password' => $password
    ]);

    if (isset($result['error'])) {
        jsonError($result['error'], $result['code'] ?? 401);
    }

    // Ensure profile exists (covers Google sign-in and other providers)
    if (isset($result['user']['id'])) {
        $sdb = supabaseService();
        $existing = $sdb->get('profiles', ['id' => 'eq.' . $result['user']['id'], 'select' => 'id', 'limit' => 1]);
        if (empty($existing) || isset($existing['error'])) {
            $meta = $result['user']['user_metadata'] ?? [];
            $name = $meta['display_name'] ?? $meta['full_name'] ?? $meta['name'] ?? explode('@', $email)[0];
            $sdb->insert('profiles', [
                'id' => $result['user']['id'],
                'display_name' => $name,
                'username' => $name,
                'avatar_url' => $meta['avatar_url'] ?? $meta['picture'] ?? null,
                'coins' => 0,
                'gems' => 0,
                'xp' => 0,
                'level' => 1,
                'daily_streak' => 0,
            ]);
        }
    }

    jsonResponse([
        'access_token' => $result['access_token'],
        'refresh_token' => $result['refresh_token'],
        'user' => $result['user']
    ]);
}

function handleGuest(): void {
    // Create an anonymous Supabase user — gives them a real token + profile
    $ch = curl_init(SUPABASE_AUTH . '/signup');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'apikey: ' . SUPABASE_ANON_KEY,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, '{}');
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $res = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code >= 400 || !$res) {
        jsonError('Guest login failed', 500);
    }

    $data = json_decode($res, true);
    if (!isset($data['access_token']) || !isset($data['user']['id'])) {
        jsonError('Guest login failed', 500);
    }

    $userId = $data['user']['id'];

    // Ensure guest profile has proper display name
    $sdb = supabaseService();
    $existing = $sdb->get('profiles', ['id' => 'eq.' . $userId, 'select' => 'id,display_name', 'limit' => 1]);
    if (is_array($existing) && !isset($existing['error']) && !empty($existing)) {
        $current = $existing[0];
        if (!$current['display_name'] || $current['display_name'] === 'لاعب جديد' || $current['display_name'] === 'Player') {
            $sdb->update('profiles', ['display_name' => 'ضيف', 'username' => 'guest_' . substr($userId, 0, 8)], ['id' => 'eq.' . $userId]);
        }
    } else {
        $sdb->insert('profiles', [
            'id' => $userId,
            'display_name' => 'ضيف',
            'username' => 'guest_' . substr($userId, 0, 8),
            'coins' => 0,
            'gems' => 0,
            'xp' => 0,
            'level' => 1,
            'daily_streak' => 0,
        ]);
    }

    // Fetch profile to return
    $db = supabase($data['access_token']);
    $profiles = $db->get('profiles', ['id' => 'eq.' . $userId, 'select' => '*', 'limit' => 1]);
    $profile = is_array($profiles) && !empty($profiles) && !isset($profiles['error']) ? $profiles[0] : null;

    jsonResponse([
        'access_token' => $data['access_token'],
        'refresh_token' => $data['refresh_token'],
        'user' => $data['user'],
        'profile' => $profile ?? ['id' => $userId, 'display_name' => 'ضيف', 'level' => 1, 'coins' => 0, 'gems' => 0]
    ]);
}

function handleRefresh(array $input): void {
    $refreshToken = $input['refresh_token'] ?? '';
    if (!$refreshToken) {
        jsonError('Refresh token required');
    }

    $result = supabaseAuth('POST', 'token?grant_type=refresh_token', [
        'refresh_token' => $refreshToken
    ]);

    if (isset($result['error'])) {
        jsonError($result['error'], $result['code'] ?? 401);
    }

    jsonResponse([
        'access_token' => $result['access_token'],
        'refresh_token' => $result['refresh_token'],
        'user' => $result['user']
    ]);
}

function handleLogout(): void {
    $token = getAuthToken();
    if ($token) {
        supabaseAuth('POST', 'logout', null, $token);
    }
    jsonResponse(['success' => true]);
}

function handleMe(): void {
    $token = requireAuth();
    $user = verifyToken($token);
    if (!$user) {
        jsonError('Invalid token', 401);
    }
    jsonResponse([
        'id' => $user['id'],
        'email' => $user['email'] ?? null,
        'provider' => $user['app_metadata']['provider'] ?? 'email',
        'created_at' => $user['created_at'] ?? null
    ]);
}

function handleDeleteAccount(array $input): void {
    $token = requireAuth();
    $user = verifyToken($token);
    if (!$user) {
        jsonError('Invalid token', 401);
    }

    $userId = $user['id'];
    $provider = $user['app_metadata']['provider'] ?? 'email';

    if ($provider === 'email') {
        $password = $input['password'] ?? '';
        if (!$password) {
            jsonError('Password required to delete account');
        }
        $verify = supabaseAuth('POST', 'token?grant_type=password', [
            'email' => $user['email'],
            'password' => $password
        ]);
        if (isset($verify['error'])) {
            jsonError('Incorrect password', 403);
        }
    } else {
        if (empty($input['confirm'])) {
            jsonError('Confirmation required to delete account');
        }
    }

    $sdb = supabaseService();
    $sdb->delete('profiles', ['id' => 'eq.' . $userId]);

    $url = SUPABASE_AUTH . '/admin/users/' . $userId;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'apikey: ' . SUPABASE_SERVICE_KEY,
        'Authorization: Bearer ' . SUPABASE_SERVICE_KEY,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode >= 400) {
        jsonError('Failed to delete account', 500);
    }

    jsonResponse(['success' => true]);
}
