<?php
require_once __DIR__ . '/auth_helper.php';
header('Content-Type: application/json; charset=UTF-8');

function json_out(array $data, int $code=200): void { http_response_code($code); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit; }
function require_user_json(): array { $u = currentUser(); if (!$u) json_out(['success'=>false,'error'=>'Please login first.'], 401); return $u; }

$action = $_POST['action'] ?? $_GET['action'] ?? '';
try {
    if ($action === 'register') {
        $countryCode = strtoupper(trim((string)($_POST['country_code'] ?? 'BD')));
        [$cc,$country,$dial] = country_from_code($countryCode);
        $phone = normalize_phone_selected((string)($_POST['phone'] ?? ''), $cc, (string)($_POST['dial_code'] ?? $dial));
        $password = (string)($_POST['password'] ?? '');
        $confirm = (string)($_POST['confirm'] ?? '');
        if ($phone === '' || strlen(preg_replace('/\D+/', '', $phone)) < 10) json_out(['success'=>false,'error'=>'Valid phone number required.'], 422);
        if (strlen($password) < 4) json_out(['success'=>false,'error'=>'Password must be at least 4 characters.'], 422);
        if ($password !== $confirm) json_out(['success'=>false,'error'=>'Passwords do not match.'], 422);
        if (findUserByPhone($phone)) json_out(['success'=>false,'error'=>'This phone is already registered.'], 409);
        $id = $phone; // UID/internal id uses the registered mobile number
        $avatar = strtoupper(substr(preg_replace('/\D+/', '', $phone), -2));
        $ref = strtoupper(substr(md5($id . $phone . microtime(true)), 0, 8));
        $stmt = pdo()->prepare('INSERT INTO users(id,phone,password_hash,country_code,country_name,dial_code,balance,bonus,safe_income,status,avatar,invite_code,referral_code,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
        $stmt->execute([$id,$phone,password_hash($password, PASSWORD_DEFAULT),$cc,$country,$dial,0,0,0,'active',$avatar,$ref,$ref,now_sql()]);
        addTransaction($id, 'register', 0, 'success', 'Account created');
        json_out(['success'=>true,'message'=>'Registration successful. Please login.','phone'=>$phone,'country'=>$country]);
    }

    if ($action === 'login') {
        $phone = normalize_phone_for_country((string)($_POST['phone'] ?? ''));
        $password = (string)($_POST['password'] ?? '');
        $user = findUserByPhone($phone);
        if (!$user || !password_verify($password, (string)($user['password_hash'] ?? ''))) json_out(['success'=>false,'error'=>'Wrong phone or password.'], 401);
        if (($user['status'] ?? 'active') !== 'active') json_out(['success'=>false,'error'=>'Your account is not active.'], 403);
        $_SESSION['user_id'] = $user['id'];
        updateUserById($user['id'], ['last_login'=>now_sql()]);
        json_out(['success'=>true,'message'=>'Login successful.']);
    }

    if ($action === 'logout') {
        unset($_SESSION['user_id']);
        json_out(['success'=>true]);
    }

    if ($action === 'balance') {
        $u = require_user_json();
        json_out(['success'=>true,'balance'=>(float)$u['balance'],'formatted'=>money($u['balance']),'country_code'=>$u['country_code']]);
    }

    if ($action === 'deposit_request') {
        $u = require_user_json();
        $amount = round((float)($_POST['amount'] ?? 0), 2);
        $methodId = (int)($_POST['method_id'] ?? 0);
        $trxid = trim((string)($_POST['trxid'] ?? ''));
        if ($amount <= 0) json_out(['success'=>false,'error'=>'Enter valid deposit amount.'], 422);
        if ($trxid === '') json_out(['success'=>false,'error'=>'Transaction ID is required.'], 422);
        $stmt = pdo()->prepare('SELECT * FROM payment_methods WHERE id=? AND country_code=? AND active=1 LIMIT 1');
        $stmt->execute([$methodId, $u['country_code']]);
        $m = $stmt->fetch();
        if (!$m) json_out(['success'=>false,'error'=>'Invalid payment method for your account country.'], 422);
        $id = uniqid('DEP', true);
        $stmt = pdo()->prepare('INSERT INTO deposit_requests(id,user_id,phone,country_code,amount,method_id,method_key,method_label,wallet_number,trxid,status,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)');
        $stmt->execute([$id,$u['id'],$u['phone'],$u['country_code'],$amount,$m['id'],$m['method_key'],$m['label'],$m['wallet_number'],$trxid,'pending',now_sql()]);
        addTransaction($u['id'], 'deposit_request', $amount, 'pending', 'Deposit request submitted via ' . $m['label']);
        json_out(['success'=>true,'message'=>'Deposit request submitted. Admin approval required.']);
    }

    if ($action === 'withdraw_request') {
        $u = require_user_json();
        $amount = round((float)($_POST['amount'] ?? 0), 2);
        $methodKey = trim((string)($_POST['method_key'] ?? ''));
        $fullName = trim((string)($_POST['full_name'] ?? ''));
        $account = trim((string)($_POST['account_number'] ?? ''));
        $opts = withdraw_method_options($u['country_code']);
        if (!isset($opts[$methodKey])) json_out(['success'=>false,'error'=>'Select valid withdraw method.'], 422);
        if ($fullName === '' || $account === '') json_out(['success'=>false,'error'=>'Name and account number are required.'], 422);
        $min = (float)get_setting('withdraw_min','500');
        $max = (float)get_setting('withdraw_max','25000');
        $feePercent = (float)get_setting('withdraw_fee','0');
        if ($amount < $min) json_out(['success'=>false,'error'=>'Minimum withdraw is ' . money($min) . '.'], 422);
        if ($amount > $max) json_out(['success'=>false,'error'=>'Maximum withdraw is ' . money($max) . '.'], 422);
        if ((float)$u['balance'] < $amount) json_out(['success'=>false,'error'=>'Insufficient balance.'], 422);
        $fee = round($amount * $feePercent / 100, 2);
        pdo()->beginTransaction();
        $stmt = pdo()->prepare('UPDATE users SET balance=balance-? WHERE id=? AND balance>=?');
        $stmt->execute([$amount,$u['id'],$amount]);
        if ($stmt->rowCount() !== 1) { pdo()->rollBack(); json_out(['success'=>false,'error'=>'Balance update failed.'], 422); }
        $id = uniqid('WDR', true);
        $stmt = pdo()->prepare('INSERT INTO withdraw_requests(id,user_id,country_code,method_key,method_label,full_name,account_number,amount,fee,status,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)');
        $stmt->execute([$id,$u['id'],$u['country_code'],$methodKey,$opts[$methodKey],$fullName,$account,$amount,$fee,'pending',now_sql()]);
        $stmt = pdo()->prepare('INSERT INTO transactions(id,user_id,type,amount,status,note,created_at) VALUES(?,?,?,?,?,?,?)');
        $stmt->execute([uniqid('TX', true),$u['id'],'withdraw_hold',$amount,'pending','Withdraw request pending via '.$opts[$methodKey],now_sql()]);
        pdo()->commit();
        json_out(['success'=>true,'message'=>'Withdraw request submitted. Balance is locked until admin decision.']);
    }

    json_out(['success'=>false,'error'=>'Invalid action.'], 400);
} catch (Throwable $e) {
    try { $p = pdo(); if ($p->inTransaction()) $p->rollBack(); } catch (Throwable $ignore) {}
    json_out(['success'=>false,'error'=>'Server error: ' . $e->getMessage()], 500);
}
