<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../include/config.php';

header('Content-Type: application/json');

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized. Please log in.']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method.']);
    exit();
}

// ── Fetch fresh user data ─────────────────────────────────────────────────
try {
    $stmt = $pdo->prepare("SELECT id, username, referral_balance FROM users WHERE id = :uid FOR UPDATE");
    $pdo->beginTransaction();
    $stmt->execute([':uid' => $_SESSION['user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Database error. Please try again.']);
    exit();
}

if (!$user) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'User not found.']);
    exit();
}

// ── Inputs ────────────────────────────────────────────────────────────────
$amount           = floatval($_POST['amount']            ?? 0);
$method_id        = intval($_POST['method_id']           ?? 0);
$wallet_or_account = trim($_POST['wallet_or_account']    ?? '');

$min_redeem       = floatval($site_data['min_redeem']    ?? 10000);
$referral_balance = floatval($user['referral_balance']);

// ── Validation ────────────────────────────────────────────────────────────
if ($amount <= 0) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Please enter a valid amount.']);
    exit();
}
if ($amount < $min_redeem) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Minimum withdrawal is ₦' . number_format($min_redeem, 2) . '.']);
    exit();
}
if ($amount > $referral_balance) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Insufficient referral balance. You have ₦' . number_format($referral_balance, 2) . '.']);
    exit();
}
if (!$method_id) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Please select a withdrawal method.']);
    exit();
}
if (empty($wallet_or_account)) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Please provide your account/wallet details.']);
    exit();
}

// ── Fetch method ──────────────────────────────────────────────────────────
try {
    $m_stmt = $pdo->prepare("SELECT * FROM withdrawal_methods WHERE id = :id AND status = 'active' LIMIT 1");
    $m_stmt->execute([':id' => $method_id]);
    $method = $m_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Could not verify withdrawal method.']);
    exit();
}

if (!$method) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Selected withdrawal method is not available.']);
    exit();
}

// ── Method-level validation ───────────────────────────────────────────────
$method_min = floatval($method['minimum_amount']);
$method_max = floatval($method['maximum_amount'] ?? 0);

if ($amount < $method_min) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Minimum withdrawal for ' . $method['method_name'] . ' is ₦' . number_format($method_min, 2) . '.']);
    exit();
}
if ($method_max > 0 && $amount > $method_max) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Maximum withdrawal for ' . $method['method_name'] . ' is ₦' . number_format($method_max, 2) . '.']);
    exit();
}

// ── Check for pending withdrawal (prevent double-submission) ─────────────
try {
    $pending_check = $pdo->prepare("SELECT id FROM withdrawals WHERE user_id = :uid AND status = 'pending' LIMIT 1");
    $pending_check->execute([':uid' => $user['id']]);
    if ($pending_check->fetch()) {
        $pdo->rollBack();
        echo json_encode(['status' => '0', 'msg' => 'You already have a pending withdrawal request. Please wait for it to be processed.']);
        exit();
    }
} catch (PDOException $e) {
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Database error checking pending withdrawals.']);
    exit();
}

// ── Calculate fee ─────────────────────────────────────────────────────────
$fee_pct    = floatval($method['fee_percentage']);
$fee_amount = round(($amount * $fee_pct) / 100, 2);
$final_amount = round($amount - $fee_amount, 2);

// ── Process ───────────────────────────────────────────────────────────────
try {
    // Deduct from referral_balance
    $pdo->prepare(
        "UPDATE users SET referral_balance = referral_balance - :amount WHERE id = :uid"
    )->execute(['amount' => $amount, 'uid' => $user['id']]);

    // Insert withdrawal record
    $pdo->prepare(
        "INSERT INTO withdrawals
            (user_id, username, withdrawal_method_id, method_name, amount, fee_percentage,
             fee_amount, final_amount, wallet_or_account, status, ip_address, user_agent, created_at, updated_at)
         VALUES
            (:uid, :uname, :method_id, :method_name, :amount, :fee_pct,
             :fee_amount, :final_amount, :wallet, 'pending', :ip, :ua, NOW(), NOW())"
    )->execute([
        'uid'          => $user['id'],
        'uname'        => $user['username'],
        'method_id'    => $method['id'],
        'method_name'  => $method['method_name'],
        'amount'       => $amount,
        'fee_pct'      => $fee_pct,
        'fee_amount'   => $fee_amount,
        'final_amount' => $final_amount,
        'wallet'       => $wallet_or_account,
        'ip'           => $_SERVER['REMOTE_ADDR'] ?? '',
        'ua'           => $_SERVER['HTTP_USER_AGENT'] ?? '',
    ]);

    $pdo->commit();

    echo json_encode([
        'status' => '1',
        'msg'    => 'Withdrawal request submitted successfully! You will receive ₦' . number_format($final_amount, 2) . ' after the ' . $fee_pct . '% fee.',
    ]);

} catch (Exception $e) {
    $pdo->rollBack();
    error_log('[Withdrawal] Error for user ' . $user['id'] . ': ' . $e->getMessage());
    echo json_encode(['status' => '0', 'msg' => 'An error occurred. Please try again.']);
}