<?php
//Developer: CORE TECH WEB DESIGN
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once dirname(__DIR__, 2) . '/include/config.php';

// Auth check
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: ' . $site_data['web_url'] . '/signin'); exit();
}

$user_id = $_SESSION['user_id'];

// Handle withdrawal
if (isset($_GET['withdraw'])) {
    try {
        $withdrawal_fee = floatval($site_data['marketplace_listing_fee'] ?? 500);
        $stmt = $pdo->prepare("SELECT seller_balance FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $u = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$u || $u['seller_balance'] <= 0) {
            $_SESSION['mp_error'] = "No seller earnings to withdraw.";
            header('Location: ' . $site_data['web_url'] . '/user/sell-account'); exit();
        }

        $balance = $u['seller_balance'];
        $requested_amount = floatval($_GET['amount'] ?? 0);
        $max_withdraw = $balance - $withdrawal_fee;

        if ($requested_amount <= 0 || $requested_amount > $max_withdraw) {
            $_SESSION['mp_error'] = "Invalid amount. Max withdrawable: ₦" . number_format($max_withdraw, 2) . " (after ₦" . number_format($withdrawal_fee, 2) . " fee).";
            header('Location: ' . $site_data['web_url'] . '/user/sell-account'); exit();
        }

        $total_deduct = $requested_amount + $withdrawal_fee;

        if ($_GET['withdraw'] === 'bank') {
            // Bank withdrawal with custom details
            $bank_name = trim($_GET['bank'] ?? '');
            $account_number = trim($_GET['acct'] ?? '');
            $account_name = trim($_GET['name'] ?? '');

            if (empty($bank_name) || empty($account_number) || empty($account_name)) {
                $_SESSION['mp_error'] = "Please provide complete bank details.";
                header('Location: ' . $site_data['web_url'] . '/user/sell-account'); exit();
            }

            $pdo->beginTransaction();
            $pdo->prepare("UPDATE users SET seller_balance = seller_balance - ? WHERE id = ?")->execute([$total_deduct, $user_id]);
            $pdo->prepare("INSERT INTO seller_withdrawals (user_id, amount, fee, bank_name, account_number, account_name) VALUES (?, ?, ?, ?, ?, ?)")
                ->execute([$user_id, $requested_amount, $withdrawal_fee, $bank_name, $account_number, $account_name]);
            $pdo->commit();

            $_SESSION['mp_success'] = "Withdrawal of ₦" . number_format($requested_amount, 2) . " submitted to " . $bank_name . " (" . $account_number . "). Processing within 24hrs. Fee: ₦" . number_format($withdrawal_fee, 2);
        } else {
            // Wallet transfer
            $pdo->prepare("UPDATE users SET main_balance = main_balance + ?, seller_balance = seller_balance - ? WHERE id = ?")->execute([$requested_amount, $total_deduct, $user_id]);
            $_SESSION['mp_success'] = "₦" . number_format($requested_amount, 2) . " transferred to wallet! (Fee: ₦" . number_format($withdrawal_fee, 2) . ")";
        }
    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $_SESSION['mp_error'] = "Withdrawal failed. Please try again.";
    }
    header('Location: ' . $site_data['web_url'] . '/user/sell-account'); exit();
}

$account_id = intval($_GET['id'] ?? 0);

// Handle re-submit rejected listing
if (isset($_GET['resubmit']) && is_numeric($_GET['resubmit'])) {
    $pdo->prepare("UPDATE marketplace_accounts SET approval_status = 'pending', rejection_reason = '' WHERE id = ? AND seller_id = ? AND approval_status = 'rejected'")->execute([intval($_GET['resubmit']), $user_id]);
    $_SESSION['mp_success'] = "Account re-submitted for review!";
    header('Location: ' . $site_data['web_url'] . '/user/sell-account'); exit();
}

// Handle delete listing
if (isset($_GET['delete_listing']) && is_numeric($_GET['delete_listing'])) {
    $pdo->prepare("DELETE FROM marketplace_accounts WHERE id = ? AND seller_id = ? AND approval_status = 'rejected'")->execute([intval($_GET['delete_listing']), $user_id]);
    $_SESSION['mp_success'] = "Listing deleted.";
    header('Location: ' . $site_data['web_url'] . '/user/sell-account'); exit();
}

if (!$account_id) {
    $_SESSION['mp_error'] = "Invalid account.";
    header('Location: ' . $site_data['web_url'] . '/user/marketplace'); exit();
}

try {
    $pdo->beginTransaction();

    // Get account (lock row)
    $stmt = $pdo->prepare("SELECT * FROM marketplace_accounts WHERE id = ? AND status = 'available' FOR UPDATE");
    $stmt->execute([$account_id]);
    $account = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$account) {
        $pdo->rollBack();
        $_SESSION['mp_error'] = "This account is no longer available.";
        header('Location: ' . $site_data['web_url'] . '/user/marketplace'); exit();
    }

    // Get user balance
    $stmt = $pdo->prepare("SELECT main_balance FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || $user['main_balance'] < $account['price']) {
        $pdo->rollBack();
        $_SESSION['mp_error'] = "Insufficient balance. You need ₦" . number_format($account['price'], 2) . " but have ₦" . number_format($user['main_balance'], 2) . ".";
        header('Location: ' . $site_data['web_url'] . '/user/marketplace'); exit();
    }

    // Deduct balance
    $new_balance = $user['main_balance'] - $account['price'];
    $pdo->prepare("UPDATE users SET main_balance = ? WHERE id = ?")->execute([$new_balance, $user_id]);

    // Mark account as sold
    $pdo->prepare("UPDATE marketplace_accounts SET status = 'sold', buyer_id = ?, purchased_at = NOW() WHERE id = ?")->execute([$user_id, $account_id]);

    // Credit seller earnings if it's a user-listed account
    if (!empty($account['seller_id'])) {
        $seller_earnings = $account['price'];
        $pdo->prepare("UPDATE marketplace_accounts SET seller_earnings = ? WHERE id = ?")->execute([$seller_earnings, $account_id]);
        // Add to seller's seller_balance (not main_balance)
        $pdo->prepare("UPDATE users SET seller_balance = seller_balance + ? WHERE id = ?")->execute([$seller_earnings, $account['seller_id']]);
    }

    $pdo->commit();

    $_SESSION['mp_success'] = "Purchase successful! Account credentials for " . $account['username'] . " are now available below.";
    header('Location: ' . $site_data['web_url'] . '/user/marketplace'); exit();

} catch (Exception $e) {
    $pdo->rollBack();
    $_SESSION['mp_error'] = "Purchase failed. Please try again.";
    header('Location: ' . $site_data['web_url'] . '/user/marketplace'); exit();
}
