<?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 '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);
    }

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

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]);
}
