<?php
require_once __DIR__ . '/bootstrap.php';

$db  = Database::getInstance();
$uri = $_SERVER['REQUEST_URI'];

// ── POST register ────────────────────────────────────────────
if (methodIs('POST') && strpos($uri, 'register') !== false) {
    $username  = sanitize($input['username'] ?? '');
    $email     = strtolower(trim($input['email'] ?? ''));
    $password  = $input['password'] ?? '';
    $firstName = sanitize($input['first_name'] ?? '');
    $lastName  = sanitize($input['last_name'] ?? '');
    $refCode   = sanitize($input['referral_code'] ?? '');
    $country   = sanitize($input['country'] ?? '');

    if (!$username || !$email || !$password || !$firstName || !$lastName)
        jsonError('All fields are required.');
    if (!filter_var($email, FILTER_VALIDATE_EMAIL))
        jsonError('Invalid email address.');
    if (strlen($password) < 6)
        jsonError('Password must be at least 6 characters.');
    if (strlen($username) < 3 || !preg_match('/^[a-zA-Z0-9_]+$/', $username))
        jsonError('Username must be 3+ chars, letters/numbers/underscore only.');
    if ($db->fetch("SELECT id FROM users WHERE email=? LIMIT 1", [$email]))
        jsonError('Email already registered.');
    if ($db->fetch("SELECT id FROM users WHERE username=? LIMIT 1", [$username]))
        jsonError('Username already taken.');

    $referrerId = null;
    if ($refCode) {
        $ref = $db->fetch("SELECT id FROM users WHERE referral_code=? LIMIT 1", [$refCode]);
        if ($ref) $referrerId = $ref['id'];
    }

    do {
        $myCode = strtoupper(substr(md5(uniqid(rand(), true)), 0, 8));
    } while ($db->fetch("SELECT id FROM users WHERE referral_code=? LIMIT 1", [$myCode]));

    $hash   = password_hash($password, PASSWORD_BCRYPT, ['cost' => BCRYPT_COST]);
    $vtoken = bin2hex(random_bytes(32));

    $userId = $db->insert(
        "INSERT INTO users (username,email,password,first_name,last_name,country,referral_code,referred_by,email_verify_token,email_verified) VALUES (?,?,?,?,?,?,?,?,?,1)",
        [$username, $email, $hash, $firstName, $lastName, $country, $myCode, $referrerId, $vtoken]
    );

    if ($referrerId) {
        $db->query("INSERT INTO referrals (referrer_id,referee_id) VALUES (?,?)", [$referrerId, $userId]);
        $db->query("UPDATE users SET total_referrals=total_referrals+1 WHERE id=?", [$referrerId]);
    }

    $jwt = createJWT(['user_id' => $userId, 'email' => $email, 'username' => $username]);
    jsonSuccess(['token' => $jwt, 'user_id' => $userId, 'username' => $username, 'email' => $email], 'Registration successful! Welcome to Merilledge Invest.');
}

// ── POST login ───────────────────────────────────────────────
if (methodIs('POST') && strpos($uri, 'login') !== false) {
    $login    = trim($input['login'] ?? '');
    $password = $input['password'] ?? '';

    if (!$login || !$password) jsonError('Email/username and password are required.');

    $user = $db->fetch("SELECT * FROM users WHERE (email=? OR username=?) LIMIT 1", [$login, $login]);

    if (!$user || !password_verify($password, $user['password']))
        jsonError('Invalid credentials.', 401);
    if ($user['status'] === 'banned')    jsonError('Account has been banned. Contact support.', 403);
    if ($user['status'] === 'suspended') jsonError('Account is temporarily suspended. Contact support.', 403);

    $db->query("UPDATE users SET last_login=NOW(), last_ip=? WHERE id=?", [$_SERVER['REMOTE_ADDR'] ?? '', $user['id']]);

    $jwt = createJWT(['user_id' => $user['id'], 'email' => $user['email'], 'username' => $user['username']]);

    jsonSuccess([
        'token'           => $jwt,
        'id'              => $user['id'],
        'username'        => $user['username'],
        'email'           => $user['email'],
        'first_name'      => $user['first_name'],
        'last_name'       => $user['last_name'],
        'deposit_balance' => (float)$user['deposit_balance'],
        'interest_balance'=> (float)$user['interest_balance'],
        'kyc_status'      => $user['kyc_status'],
        'referral_code'   => $user['referral_code'],
    ], 'Login successful');
}

// ── POST forgot-password ──────────────────────────────────────
if (methodIs('POST') && strpos($uri, 'forgot') !== false) {
    $email = strtolower(trim($input['email'] ?? ''));
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) jsonError('Invalid email.');
    $user = $db->fetch("SELECT id,email FROM users WHERE email=? LIMIT 1", [$email]);
    if ($user) {
        $token = bin2hex(random_bytes(32));
        $exp   = date('Y-m-d H:i:s', time() + 3600);
        $db->query("UPDATE users SET reset_token=?, reset_expires=? WHERE id=?", [$token, $exp, $user['id']]);
        error_log("Password reset: " . FRONTEND_URL . "/account/reset-password.html?token=$token");
    }
    jsonSuccess([], 'If that email exists, a reset link has been sent.');
}

// ── POST reset-password ───────────────────────────────────────
if (methodIs('POST') && strpos($uri, 'reset') !== false) {
    $token    = sanitize($input['token'] ?? '');
    $password = $input['password'] ?? '';
    if (!$token || strlen($password) < 6) jsonError('Token and new password (6+ chars) are required.');
    $user = $db->fetch("SELECT id FROM users WHERE reset_token=? AND reset_expires>NOW() LIMIT 1", [$token]);
    if (!$user) jsonError('Invalid or expired reset token.');
    $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => BCRYPT_COST]);
    $db->query("UPDATE users SET password=?, reset_token=NULL, reset_expires=NULL WHERE id=?", [$hash, $user['id']]);
    jsonSuccess([], 'Password reset successfully. You can now log in.');
}

// ── GET me ────────────────────────────────────────────────────
if (methodIs('GET')) {
    $auth = requireAuth();
    $user = $db->fetch("SELECT id,username,email,first_name,last_name,phone,country,avatar,deposit_balance,interest_balance,total_invested,total_withdrawn,total_referrals,kyc_status,two_factor_enabled,referral_code,last_login,created_at FROM users WHERE id=?", [$auth['user_id']]);
    if (!$user) jsonError('User not found.', 404);
    jsonSuccess($user);
}

jsonSuccess([], 'OK');
