<?php
require_once __DIR__ . '/../common/config.php';
while (ob_get_level()) ob_end_clean();
$authAjax = strtolower((string)($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '')) === 'xmlhttprequest'
    || stripos((string)($_SERVER['HTTP_ACCEPT'] ?? ''), 'application/json') !== false;
if ($authAjax) {
    header('Content-Type: application/json; charset=utf-8');
}

function auth_json($status, $message, $extra = []) {
    global $authAjax;
    if (!$authAjax) {
        if ($status === 'success') {
            header('Location: ../index.php');
        } else {
            $target = (($_POST['action'] ?? '') === 'login') ? '../login.php' : '../register.php';
            header('Location: ' . $target . '?error=' . rawurlencode($message));
        }
        exit;
    }
    echo json_encode(array_merge(['status' => $status, 'message' => $message], $extra), JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
        auth_json('error', 'Invalid request');
    }
    $action = $_POST['action'] ?? '';

    if ($action === 'register') {
        $name = trim((string)($_POST['name'] ?? ''));
        $email = strtolower(trim((string)($_POST['email'] ?? '')));
        $phone = trim((string)($_POST['phone'] ?? ''));
        $password = (string)($_POST['password'] ?? '');

        if ($name === '' || $email === '' || $password === '') {
            auth_json('error', 'Name, email and password are required');
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            auth_json('error', 'Enter a valid email address');
        }
        if (strlen($password) < 4) {
            auth_json('error', 'Password must be at least 4 characters');
        }

        $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ?');
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            auth_json('error', 'This email is already registered');
        }

        $hash = password_hash($password, PASSWORD_DEFAULT);
        $pin = (string)random_int(100000, 999999);
        $code = strtoupper(substr(preg_replace('/[^A-Za-z]/', '', $name) . 'MANGO', 0, 5)) . random_int(10, 99);

        $ok = $pdo->prepare('INSERT INTO users (name, email, phone, password, balance, support_pin, referral_code, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
            ->execute([$name, $email, $phone, $hash, 0, $pin, $code, 'active']);
        if (!$ok) {
            auth_json('error', 'Registration failed. Please try again.');
        }

        session_regenerate_id(true);
        $_SESSION['user_id'] = $pdo->lastInsertId();
        $_SESSION['user_name'] = $name;
        $_SESSION['user_balance'] = 0;
        $_SESSION['support_pin'] = $pin;

        auth_json('success', 'Account created successfully!', ['redirect' => 'index.php']);
    }

    if ($action === 'login') {
        $email = strtolower(trim((string)($_POST['email'] ?? '')));
        $password = (string)($_POST['password'] ?? '');
        if ($email === '' || $password === '') {
            auth_json('error', 'Enter email and password');
        }
        $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        if (!$user) {
            auth_json('error', 'Account not found');
        }
        if (($user['status'] ?? 'active') === 'blocked') {
            auth_json('error', 'Your account is blocked');
        }
        if (!password_verify($password, $user['password'] ?? '')) {
            auth_json('error', 'Invalid email or password');
        }
        session_regenerate_id(true);
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['user_balance'] = $user['balance'] ?? 0;
        $_SESSION['support_pin'] = $user['support_pin'] ?? '';
        auth_json('success', 'Login successful!', ['redirect' => 'index.php']);
    }

    auth_json('error', 'Unknown request');
} catch (Throwable $e) {
    auth_json('error', 'Something went wrong. Please try again.');
}
