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

$db = Database::getInstance();

// GET /invest/plans — public
if ($method === 'GET' && strpos($uri, '/invest/plans') !== false) {
    $plans = $db->fetchAll("SELECT * FROM plans WHERE status=1 ORDER BY min_deposit ASC");
    jsonSuccess(['plans' => $plans]);
}

// POST /invest/create — requires auth
if ($method === 'POST' && strpos($uri, '/invest/create') !== false) {
    $auth   = requireAuth();
    $userId = $auth['user_id'];

    $planId = (int)($input['plan_id'] ?? 0);
    $amount = (float)($input['amount'] ?? 0);
    $wallet = sanitize($input['wallet'] ?? 'deposit'); // 'deposit' or 'interest'

    if (!$planId || $amount <= 0) jsonError('Plan and amount are required.');

    $plan = $db->fetch("SELECT * FROM plans WHERE id=? AND status=1 LIMIT 1", [$planId]);
    if (!$plan) jsonError('Invalid investment plan.');

    if ($amount < $plan['min_deposit']) jsonError("Minimum deposit for this plan is $" . number_format($plan['min_deposit'], 2));
    if ($amount > $plan['max_deposit']) jsonError("Maximum deposit for this plan is $" . number_format($plan['max_deposit'], 2));

    // Check user balance
    $user = $db->fetch("SELECT deposit_balance, interest_balance FROM users WHERE id=?", [$userId]);
    $balance = $wallet === 'interest' ? (float)$user['interest_balance'] : (float)$user['deposit_balance'];

    if ($balance < $amount) jsonError("Insufficient balance. Available: $" . number_format($balance, 2));

    // Calculate returns
    if ($plan['roi_type'] === 'daily') {
        $roiAmount  = ($amount * $plan['roi'] / 100) * $plan['duration'];
    } else {
        $roiAmount  = $amount * $plan['roi'] / 100;
    }
    $totalReturn = $amount + $roiAmount; // capital back + ROI

    $expiresAt = date('Y-m-d H:i:s', strtotime("+{$plan['duration']} days"));

    // Deduct from user balance
    if ($wallet === 'interest') {
        $db->query("UPDATE users SET interest_balance=interest_balance-?, total_invested=total_invested+? WHERE id=?", [$amount, $amount, $userId]);
    } else {
        $db->query("UPDATE users SET deposit_balance=deposit_balance-?, total_invested=total_invested+? WHERE id=?", [$amount, $amount, $userId]);
    }

    // Create investment
    $investId = $db->insert(
        "INSERT INTO investments (user_id,plan_id,amount,roi_amount,total_return,started_at,expires_at) VALUES (?,?,?,?,?,NOW(),?)",
        [$userId, $planId, $amount, $roiAmount, $totalReturn, $expiresAt]
    );

    // Transaction record
    $db->insert(
        "INSERT INTO transactions (user_id,type,amount,description,reference_id,wallet) VALUES (?,?,?,?,?,?)",
        [$userId, 'investment', $amount, "Investment in {$plan['name']} Plan", $investId, $wallet]
    );

    // Pay referral bonus if applicable
    $referral = $db->fetch("SELECT r.*, u.deposit_balance FROM referrals r JOIN users u ON r.referrer_id=u.id WHERE r.referee_id=? AND r.status='pending' LIMIT 1", [$userId]);
    if ($referral) {
        $bonus = $amount * $plan['referral_bonus'] / 100;
        $db->query("UPDATE users SET deposit_balance=deposit_balance+? WHERE id=?", [$bonus, $referral['referrer_id']]);
        $db->query("UPDATE referrals SET bonus_amount=?, status='paid', investment_id=? WHERE id=?", [$bonus, $investId, $referral['id']]);
        $db->insert(
            "INSERT INTO transactions (user_id,type,amount,description,reference_id,wallet) VALUES (?,?,?,?,?,?)",
            [$referral['referrer_id'], 'referral', $bonus, "Referral bonus from investment #{$investId}", $investId, 'deposit']
        );
    }

    jsonSuccess([
        'investment_id' => $investId,
        'amount'        => $amount,
        'roi_amount'    => $roiAmount,
        'total_return'  => $totalReturn,
        'expires_at'    => $expiresAt,
    ], "Investment of $" . number_format($amount, 2) . " in {$plan['name']} Plan started successfully!");
}

// GET /invest/history
if ($method === 'GET' && strpos($uri, '/invest/history') !== false) {
    $auth   = requireAuth();
    $userId = $auth['user_id'];
    $page   = max(1, (int)($_GET['page'] ?? 1));
    $limit  = 20;
    $offset = ($page - 1) * $limit;

    $total = $db->fetch("SELECT COUNT(*) as cnt FROM investments WHERE user_id=?", [$userId])['cnt'];
    $investments = $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=? ORDER BY i.created_at DESC LIMIT $limit OFFSET $offset",
        [$userId]
    );

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