<?php

require_once __DIR__ . '/../config/database.php';

header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

if ($action === 'login') {
    $email = $input['email'] ?? '';
    $password = $input['password'] ?? '';

    if (!$email || !$password) {
        http_response_code(400);
        echo json_encode(['error' => 'البريد وكلمة المرور مطلوبين']);
        exit;
    }

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

    if ($result['status'] !== 200) {
        $msg = $result['data']['error_description'] ?? $result['data']['msg'] ?? 'بيانات الدخول غير صحيحة';
        http_response_code(401);
        echo json_encode(['error' => $msg]);
        exit;
    }

    echo json_encode([
        'access_token' => $result['data']['access_token'],
        'refresh_token' => $result['data']['refresh_token'],
        'user' => $result['data']['user'],
    ]);

} elseif ($action === 'register') {
    $email = $input['email'] ?? '';
    $password = $input['password'] ?? '';
    $username = $input['username'] ?? '';

    if (!$email || !$password || !$username) {
        http_response_code(400);
        echo json_encode(['error' => 'جميع الحقول مطلوبة']);
        exit;
    }

    if (strlen($password) < 6) {
        http_response_code(400);
        echo json_encode(['error' => 'كلمة المرور يجب ان تكون 6 احرف على الاقل']);
        exit;
    }

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

    if ($result['status'] !== 200 && $result['status'] !== 201) {
        $msg = $result['data']['error_description'] ?? $result['data']['msg'] ?? 'فشل التسجيل';
        http_response_code(400);
        echo json_encode(['error' => $msg]);
        exit;
    }

    if (isset($result['data']['access_token'])) {
        echo json_encode([
            'access_token' => $result['data']['access_token'],
            'refresh_token' => $result['data']['refresh_token'],
            'user' => $result['data']['user'],
        ]);
    } else {
        echo json_encode(['message' => 'تم التسجيل بنجاح، يرجى تاكيد البريد']);
    }

} elseif ($action === 'refresh') {
    $refreshToken = $input['refresh_token'] ?? '';

    if (!$refreshToken) {
        http_response_code(400);
        echo json_encode(['error' => 'refresh_token مطلوب']);
        exit;
    }

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

    if ($result['status'] !== 200) {
        http_response_code(401);
        echo json_encode(['error' => 'الجلسة منتهية']);
        exit;
    }

    echo json_encode([
        'access_token' => $result['data']['access_token'],
        'refresh_token' => $result['data']['refresh_token'],
    ]);

} else {
    http_response_code(400);
    echo json_encode(['error' => 'action غير معروف']);
}
