<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

include_once __DIR__ . '/connection.php'; // $conn (mysqli)
include_once __DIR__ . '/unified_config.php';

function human_upload_err($code) {
    return [
        UPLOAD_ERR_OK         => 'OK',
        UPLOAD_ERR_INI_SIZE   => 'Exceeds upload_max_filesize',
        UPLOAD_ERR_FORM_SIZE  => 'Exceeds MAX_FILE_SIZE in form',
        UPLOAD_ERR_PARTIAL    => 'Partial upload',
        UPLOAD_ERR_NO_FILE    => 'No file uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing temp dir',
        UPLOAD_ERR_CANT_WRITE => 'Cannot write to disk',
        UPLOAD_ERR_EXTENSION  => 'Blocked by PHP extension'
    ][$code] ?? ('Unknown error '.$code);
}

/* ---------- Parse body: JSON or form/x-www-multipart ---------- */
$ct  = $_SERVER['CONTENT_TYPE'] ?? '';
$raw = file_get_contents('php://input');
$data = null;

if (stripos($ct, 'application/json') !== false) {
    $data = json_decode($raw, true);
}
if (!is_array($data)) $data = $_POST;

/* ---------- A) Fetch accounts ---------- */
if (($data['action'] ?? '') === 'fetch_accounts') {
    $user_id = (int)($data['user_id'] ?? 0);
    $stmt = $conn->prepare("SELECT trade_id, email, account_name, account_type FROM liveaccounts WHERE user_id=?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $accounts = [];
    while ($row = $res->fetch_assoc()) $accounts[] = $row;
    echo json_encode(['success'=>true, 'accounts'=>$accounts]);
    exit;
}

/* ---------- B) Recent deposits ---------- */
if ((isset($_GET['action']) && $_GET['action']==='recent') || (($data['action'] ?? '')==='recent')) {
    $user_id = (int)($data['user_id'] ?? 0);
    if ($user_id <= 0) {
        echo json_encode(['success'=>false, 'error'=>'Invalid user_id']); exit;
    }

    $stmt = $conn->prepare("
        SELECT dr.*, l.email, l.account_name, l.account_type
        FROM deposit_requests dr
        JOIN liveaccounts l ON l.trade_id = dr.trade_id
        WHERE dr.user_id = ?
        ORDER BY dr.created_at DESC LIMIT 5
    ");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $out = [];
    while ($r = $res->fetch_assoc()) {
        $out[] = [
            'email'            => $r['email'],
            'amount'           => $r['amount'],
            'type'             => $r['type'],
            'account_name'     => $r['account_name'],
            'account_type'     => $r['account_type'],
            'status'           => $r['status'],
            'created_at'       => $r['created_at'],
            'transaction_proof'=> $r['transaction_proof'],
        ];
    }
    echo json_encode(['success'=>true, 'deposits'=>$out]);
    exit;
}

/* ---------- C) Create deposit request ---------- */
$trade_id = trim((string)($data['trade_id'] ?? ''));
$amount   = (float)($data['amount'] ?? 0);
$type     = (string)($data['type'] ?? 'balance');
$comment  = (string)($data['comment'] ?? 'Deposit via UI');
$transaction_proof = $data['transaction_proof'] ?? null;

/* Handle uploaded file */
if (isset($_FILES['transaction_proof']) && $_FILES['transaction_proof']['error'] !== UPLOAD_ERR_NO_FILE) {
    $f = $_FILES['transaction_proof'];
    if ($f['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success'=>false,'error'=>"Upload error: ".human_upload_err($f['error'])]); exit;
    }

    $webRoot = rtrim($_SERVER['DOCUMENT_ROOT'] ?? dirname(__DIR__), DIRECTORY_SEPARATOR);
    $uploadsDirAbs = $webRoot . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR;
    if (!is_dir($uploadsDirAbs)) @mkdir($uploadsDirAbs, 0755, true);

    $ext = pathinfo($f['name'], PATHINFO_EXTENSION);
    $nameBase = preg_replace('/[^a-zA-Z0-9_.-]/','_', pathinfo($f['name'], PATHINFO_FILENAME));
    $newName = uniqid('proof_', true) . '_' . $nameBase . '.' . $ext;
    $destAbs = $uploadsDirAbs . $newName;

    if (!move_uploaded_file($f['tmp_name'], $destAbs)) {
        echo json_encode(['success'=>false,'error'=>'Failed to store uploaded file']); exit;
    }

    $transaction_proof = '/uploads/' . $newName;
}

/* Validate trade_id & amount */
if ($trade_id === '' || $amount <= 0) {
    echo json_encode(['success'=>false,'error'=>'Invalid trade ID or amount']); exit;
}

/* Verify account exists */
$stmt = $conn->prepare("SELECT id, user_id FROM liveaccounts WHERE trade_id=? LIMIT 1");
$stmt->bind_param("s", $trade_id);
$stmt->execute();
$userRow = $stmt->get_result()->fetch_assoc();
if (!$userRow) {
    echo json_encode(['success'=>false,'error'=>'User not found']); exit;
}

/* Insert deposit request */
$stmt = $conn->prepare("
    INSERT INTO deposit_requests
    (user_id, trade_id, amount, type, comment, transaction_proof, status)
    VALUES (?, ?, ?, ?, ?, ?, 'pending')
");
$stmt->bind_param(
    "isdsss",
    $userRow['user_id'],
    $trade_id,
    $amount,
    $type,
    $comment,
    $transaction_proof
);

if ($stmt->execute()) {
    $depositId = $conn->insert_id;
    
    // ------------------
    // Send deposit request submission email
    // ------------------
    $emailSent = false;
    if (EMAIL_AUTOMATION_ENABLED) {
        // Get user details for email
        $stmtUserDetails = $conn->prepare("SELECT email, first_name, last_name FROM loginusers WHERE id = ?");
        $stmtUserDetails->bind_param("i", $userRow['user_id']);
        $stmtUserDetails->execute();
        $userResult = $stmtUserDetails->get_result();
        
        if ($userDetails = $userResult->fetch_assoc()) {
            $mailSystem = getMailSystem();
            $fullName = trim($userDetails['first_name'] . ' ' . $userDetails['last_name']);
            
            $emailResult = $mailSystem->sendDepositRequestSubmitted(
                $userDetails['email'], 
                $fullName, 
                $amount, 
                'USD',
                $type,
                'DEP-' . $depositId
            );
            
            $emailSent = $emailResult['success'];
            
            // Log email result
            if (!$emailResult['success']) {
                error_log("Failed to send deposit request email to " . $userDetails['email'] . ": " . $emailResult['message']);
            }
        }
        $stmtUserDetails->close();
    }
    
    echo json_encode([
        'success'=>true,
        'message'=>'Deposit request submitted successfully. Waiting for admin approval.',
        'ticket'=>$depositId,
        'proof'=>$transaction_proof,
        'email_sent'=>$emailSent
    ]);
} else {
    echo json_encode(['success'=>false, 'error'=>'Failed to submit deposit request: '.$stmt->error]);
}
