<?php
require_once __DIR__ . '/bootstrap.php';
// endpoints/user.php — handles all /user/* routes

$auth = requireAuth();
$userId = $auth['user_id'];
$db = Database::getInstance();

// GET /user/dashboard
if ($method === 'GET' && strpos($uri, '/user/dashboard') !== false) {
    $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,referral_code,two_factor_enabled,last_login FROM users WHERE id=?",
        [$userId]
    );

    // Active investments
    $activeInvestments = $db->fetchAll(
        "SELECT i.*, p.name as plan_name, p.roi, p.roi_type, p.duration FROM investments i JOIN plans p ON i.plan_id=p.id WHERE i.user_id=? AND i.status='active' ORDER BY i.created_at DESC",
        [$userId]
    );

    // Recent transactions (last 10)
    $recentTx = $db->fetchAll(
        "SELECT * FROM transactions WHERE user_id=? ORDER BY created_at DESC LIMIT 10",
        [$userId]
    );

    // Stats
    $totalDeposited = $db->fetch("SELECT COALESCE(SUM(amount),0) as total FROM deposits WHERE user_id=? AND status='approved'", [$userId])['total'];
    $totalWithdrawn = $db->fetch("SELECT COALESCE(SUM(amount),0) as total FROM withdrawals WHERE user_id=? AND status='approved'", [$userId])['total'];
    $activeCount    = $db->fetch("SELECT COUNT(*) as cnt FROM investments WHERE user_id=? AND status='active'", [$userId])['cnt'];
    $pendingDeposit = $db->fetch("SELECT COUNT(*) as cnt FROM deposits WHERE user_id=? AND status='pending'", [$userId])['cnt'];
    $pendingWithdraw= $db->fetch("SELECT COUNT(*) as cnt FROM withdrawals WHERE user_id=? AND status='pending'", [$userId])['cnt'];

    jsonSuccess([
        'user'               => $user,
        'active_investments' => $activeInvestments,
        'recent_transactions'=> $recentTx,
        'stats' => [
            'deposit_balance'  => (float)$user['deposit_balance'],
            'interest_balance' => (float)$user['interest_balance'],
            'total_deposited'  => (float)$totalDeposited,
            'total_withdrawn'  => (float)$totalWithdrawn,
            'total_invested'   => (float)$user['total_invested'],
            'active_investments'=> (int)$activeCount,
            'pending_deposits' => (int)$pendingDeposit,
            'pending_withdrawals'=> (int)$pendingWithdraw,
            'total_referrals'  => (int)$user['total_referrals'],
        ]
    ]);
}

// GET /user/profile
if ($method === 'GET' && strpos($uri, '/user/profile') !== false && strpos($uri, 'update') === false) {
    $user = $db->fetch("SELECT id,username,email,first_name,last_name,phone,country,avatar,kyc_status,referral_code,two_factor_enabled,created_at FROM users WHERE id=?", [$userId]);
    jsonSuccess(['user' => $user]);
}

// POST /user/profile/update
if ($method === 'POST' && strpos($uri, '/user/profile/update') !== false) {
    $firstName = sanitize($input['first_name'] ?? '');
    $lastName  = sanitize($input['last_name'] ?? '');
    $phone     = sanitize($input['phone'] ?? '');
    $country   = sanitize($input['country'] ?? '');

    if (!$firstName || !$lastName) jsonError('First and last name are required.');

    $db->query(
        "UPDATE users SET first_name=?, last_name=?, phone=?, country=? WHERE id=?",
        [$firstName, $lastName, $phone, $country, $userId]
    );
    jsonSuccess([], 'Profile updated successfully.');
}

// POST /user/change-password
if ($method === 'POST' && strpos($uri, '/user/change-password') !== false) {
    $current = $input['current_password'] ?? '';
    $new     = $input['new_password'] ?? '';
    $confirm = $input['confirm_password'] ?? '';

    if (!$current || !$new || !$confirm) jsonError('All fields are required.');
    if ($new !== $confirm) jsonError('New passwords do not match.');
    if (strlen($new) < 6) jsonError('New password must be at least 6 characters.');

    $user = $db->fetch("SELECT password FROM users WHERE id=?", [$userId]);
    if (!password_verify($current, $user['password'])) jsonError('Current password is incorrect.');

    $hash = password_hash($new, PASSWORD_BCRYPT, ['cost' => BCRYPT_COST]);
    $db->query("UPDATE users SET password=? WHERE id=?", [$hash, $userId]);
    jsonSuccess([], 'Password changed successfully.');
}

// GET /user/referrals
if ($method === 'GET' && strpos($uri, '/user/referrals') !== false) {
    $user = $db->fetch("SELECT referral_code, total_referrals FROM users WHERE id=?", [$userId]);
    $referrals = $db->fetchAll(
        "SELECT u.username, u.email, u.first_name, u.last_name, u.created_at, r.bonus_amount, r.status
         FROM referrals r JOIN users u ON r.referee_id=u.id
         WHERE r.referrer_id=? ORDER BY r.created_at DESC",
        [$userId]
    );
    $totalEarned = $db->fetch("SELECT COALESCE(SUM(bonus_amount),0) as total FROM referrals WHERE referrer_id=? AND status='paid'", [$userId])['total'];
    jsonSuccess([
        'referral_code'  => $user['referral_code'],
        'referral_link'  => FRONTEND_URL . '/account/register.html?ref=' . $user['referral_code'],
        'total_referrals'=> (int)$user['total_referrals'],
        'total_earned'   => (float)$totalEarned,
        'referrals'      => $referrals,
    ]);
}

// GET /user/transactions
if ($method === 'GET' && strpos($uri, '/user/transactions') !== false) {
    $page  = max(1, (int)($_GET['page'] ?? 1));
    $limit = 20;
    $offset= ($page - 1) * $limit;
    $type  = sanitize($_GET['type'] ?? '');

    $where = "WHERE user_id=?";
    $params = [$userId];
    if ($type) { $where .= " AND type=?"; $params[] = $type; }

    $total = $db->fetch("SELECT COUNT(*) as cnt FROM transactions $where", $params)['cnt'];
    $txs   = $db->fetchAll("SELECT * FROM transactions $where ORDER BY created_at DESC LIMIT $limit OFFSET $offset", $params);

    jsonSuccess([
        'transactions' => $txs,
        'total'        => (int)$total,
        'page'         => $page,
        'pages'        => ceil($total / $limit),
    ]);
}
