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

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

// GET /deposit/methods
if ($method === 'GET' && strpos($uri, '/deposit/methods') !== false) {
    $wallets = $db->fetchAll("SELECT currency, network, address, qr_code FROM wallet_addresses WHERE status=1");
    foreach ($wallets as &$w) {
        $w['qr_url'] = !empty($w['qr_code']) ? SITE_URL . '/backend/uploads/qr/' . $w['qr_code'] : null;
    }
    jsonSuccess(['methods' => $wallets]);
}

// POST /deposit/submit
if ($method === 'POST' && strpos($uri, '/deposit/submit') !== false) {
    // Support both FormData (multipart) and JSON body
    // FormData fields arrive in $_POST; JSON arrives in $input (php://input)
    $currency = sanitize($_POST['currency'] ?? $input['currency'] ?? '');
    $amount   = (float)($_POST['amount']   ?? $input['amount']   ?? 0);
    $txHash   = sanitize($_POST['tx_hash'] ?? $input['tx_hash']  ?? '');

    if (!$currency || $amount <= 0) jsonError('Currency and amount are required.');
    if ($amount < 10) jsonError('Minimum deposit is $10.');

    $wallet = $db->fetch("SELECT address FROM wallet_addresses WHERE currency=? AND status=1 LIMIT 1", [$currency]);
    if (!$wallet) jsonError('Selected currency is not available.');

    // Handle proof image upload
    $proofImage = null;
    // Frontend sends file as 'proof_image'
    $proofField = !empty($_FILES['proof_image']) ? 'proof_image' : 'proof';
    if (!empty($_FILES[$proofField]) && $_FILES[$proofField]['error'] === UPLOAD_ERR_OK) {
        $allowed = ['image/jpeg','image/png','image/gif','image/webp'];
        if (!in_array($_FILES[$proofField]['type'], $allowed)) jsonError('Invalid file type for proof.');
        $ext      = pathinfo($_FILES[$proofField]['name'], PATHINFO_EXTENSION);
        $filename = 'deposit_' . $userId . '_' . time() . '.' . $ext;
        $uploadDir = __DIR__ . '/../../uploads/proofs/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
        move_uploaded_file($_FILES[$proofField]['tmp_name'], $uploadDir . $filename);
        $proofImage = $filename;
    }

    $depositId = $db->insert(
        "INSERT INTO deposits (user_id, amount, currency, wallet_address, tx_hash, proof_image) VALUES (?,?,?,?,?,?)",
        [$userId, $amount, $currency, $wallet['address'], $txHash, $proofImage]
    );

    $db->insert(
        "INSERT INTO transactions (user_id,type,amount,description,reference_id,wallet,status) VALUES (?,?,?,?,?,?,?)",
        [$userId, 'deposit', $amount, "Deposit of $$amount via $currency (Pending)", $depositId, 'deposit', 'pending']
    );

    jsonSuccess([
        'deposit_id'     => $depositId,
        'wallet_address' => $wallet['address'],
        'amount'         => $amount,
        'currency'       => $currency,
    ], 'Deposit request submitted. Awaiting confirmation (usually within 30 minutes).');
}

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

    $total    = $db->fetch("SELECT COUNT(*) as cnt FROM deposits WHERE user_id=?", [$userId])['cnt'];
    $deposits = $db->fetchAll(
        "SELECT * FROM deposits WHERE user_id=? ORDER BY created_at DESC LIMIT $limit OFFSET $offset",
        [$userId]
    );
    jsonSuccess(['deposits'=>$deposits,'total'=>(int)$total,'page'=>$page,'pages'=>ceil($total/$limit)]);
}
