<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/src/SMTP.php';
require_once __DIR__ . '/PHPMailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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

/* =========================
   AUTH CHECK
========================= */
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized.']);
    exit;
}

$user_id = $_SESSION['user_id'];

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

/* =========================
   COMMON INPUTS
========================= */
$withdrawalType = $_POST['withdrawal_type'] ?? 'crypto';
$usdAmount = floatval($_POST['usdAmount'] ?? 0);

if ($usdAmount <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid withdrawal amount.']);
    exit;
}

/* =========================
   GET USER BALANCE
========================= */
$balanceStmt = $conn->prepare("SELECT account_balance FROM users WHERE id = ?");
$balanceStmt->bind_param("i", $user_id);
$balanceStmt->execute();
$user = $balanceStmt->get_result()->fetch_assoc();
$balanceStmt->close();

if (!$user || $usdAmount > $user['account_balance']) {
    echo json_encode(['success' => false, 'message' => 'Insufficient balance.']);
    exit;
}

/* =========================
   INITIALIZE OPTIONAL FIELDS
========================= */
$cryptoAmount = null;
$cryptoType = null;
$walletAddress = null;

$bankName = null;
$accountName = null;
$accountNumber = null;

/* =========================
   CRYPTO WITHDRAWAL
========================= */
if ($withdrawalType === 'crypto') {
    $cryptoAmount = $_POST['cryptoAmount'] ?? null;
    $cryptoType = $_POST['cryptoType'] ?? null;
    $walletAddress = $_POST['walletAddress'] ?? null;

    if (!$cryptoAmount || !$cryptoType || !$walletAddress) {
        echo json_encode(['success' => false, 'message' => 'All crypto fields are required.']);
        exit;
    }
}

/* =========================
   BANK WITHDRAWAL
========================= */
if ($withdrawalType === 'bank') {
    $bankName = $_POST['bankName'] ?? null;
    $accountName = $_POST['accountName'] ?? null;
    $accountNumber = $_POST['accountNumber'] ?? null;

    if (!$bankName || !$accountName || !$accountNumber) {
        echo json_encode(['success' => false, 'message' => 'All bank details are required.']);
        exit;
    }

    // Ensure crypto fields are NULL for bank withdrawal
    $cryptoAmount = null;
    $cryptoType = null;
    $walletAddress = null;
}

/* =========================
   INSERT WITHDRAWAL
========================= */
$stmt = $conn->prepare("
    INSERT INTO withdrawals (
        user_id,
        withdrawal_type,
        usd_amount,
        crypto_amount,
        crypto_type,
        wallet_address,
        bank_name,
        account_name,
        account_number,
        status
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
");

// Bind parameters (crypto_amount, crypto_type, wallet_address can be NULL)
$stmt->bind_param(
    "isdssssss",
    $user_id,
    $withdrawalType,
    $usdAmount,
    $cryptoAmount,
    $cryptoType,
    $walletAddress,
    $bankName,
    $accountName,
    $accountNumber
);

if (!$stmt->execute()) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $stmt->error]);
    exit;
}

/* =========================
   ACTIVITY LOG
========================= */
$formattedAmount = number_format($usdAmount, 2);

$description = ($withdrawalType === 'crypto')
    ? "You requested a crypto withdrawal of \$$formattedAmount ($cryptoType). Awaiting approval."
    : "You requested a bank withdrawal of \$$formattedAmount to $bankName ($accountNumber). Awaiting approval.";

$logStmt = $conn->prepare("
    INSERT INTO activity_logs (user_id, actor, action_type, description)
    VALUES (?, 'user', 'withdrawal', ?)
");
$logStmt->bind_param("is", $user_id, $description);
$logStmt->execute();
$logStmt->close();

/* =========================
   EMAIL ADMIN
========================= */
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'mail.octaltrade.net';
    $mail->SMTPAuth = true;
    $mail->Username = 'support@octaltrade.net';
    $mail->Password = '******'; // move to ENV
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    $mail->setFrom('support@octaltrade.net', 'OctalTrade Withdrawals');
    $mail->addAddress('prolificmk20@gmail.com');
    $mail->addAddress('Davehack227@gmail.com');

    $mail->isHTML(true);
    $mail->Subject = "🚨 New {$withdrawalType} Withdrawal Request";

    $mail->Body = "
        <h3>Withdrawal Request</h3>
        <p><strong>User ID:</strong> {$user_id}</p>
        <p><strong>Amount:</strong> \${$usdAmount}</p>
        <p><strong>Type:</strong> {$withdrawalType}</p>
        " . ($withdrawalType === 'crypto'
            ? "<p><strong>Crypto:</strong> {$cryptoAmount} {$cryptoType}</p>
               <p><strong>Wallet:</strong> {$walletAddress}</p>"
            : "<p><strong>Bank:</strong> {$bankName}</p>
               <p><strong>Account:</strong> {$accountName} ({$accountNumber})</p>"
        );

    $mail->send();
} catch (Exception $e) {
    // silent fail
}

/* =========================
   SUCCESS RESPONSE
========================= */
echo json_encode([
    'success' => true,
    'message' => 'Withdrawal request submitted successfully. Awaiting approval.'
]);

$stmt->close();
$conn->close();
