<?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') {
    http_response_code(200);
    exit;
}

include_once __DIR__ . "/../config.php";
include_once __DIR__ . "/../connection.php";

$input = json_decode(file_get_contents("php://input"), true);

$request_id = intval($input['request_id'] ?? 0);
$action = strtolower($input['action'] ?? ''); // 'approve' or 'reject'
$admin_remark = $input['admin_remark'] ?? '';
$transaction_id = $input['transaction_id'] ?? bin2hex(random_bytes(6));

// If no request_id, fetch all pending requests
if (!$request_id) {
    $result = $conn->query("SELECT * FROM ib_withdraw_request WHERE status=0 ORDER BY created_at DESC");
    $requests = $result->fetch_all(MYSQLI_ASSOC);
    echo json_encode([
        "success" => true,
        "message" => "Pending withdrawal requests fetched successfully",
        "requests" => $requests
    ], JSON_PRETTY_PRINT);
    exit;
}

// Fetch the specific withdraw request
$stmt = $conn->prepare("SELECT * FROM ib_withdraw_request WHERE id = ?");
$stmt->bind_param("i", $request_id);
$stmt->execute();
$result = $stmt->get_result();
$request = $result->fetch_assoc();
$stmt->close();

if (!$request) {
    echo json_encode(["success" => false, "message" => "Request not found"]);
    exit;
}

// Reject the request
if ($action === 'reject') {
    $update_stmt = $conn->prepare("UPDATE ib_withdraw_request SET status=2, updated_at=NOW() WHERE id=?");
    $update_stmt->bind_param("i", $request_id);
    $executed = $update_stmt->execute();
    $update_stmt->close();

    if ($executed) {
        echo json_encode(["success" => true, "message" => "Withdrawal request rejected successfully"]);
    } else {
        echo json_encode(["success" => false, "message" => "Failed to reject request"]);
    }
    exit;
}

// Approve the request
$ifsc = $request['ifsc'] ?? 'NA';

$insert_stmt = $conn->prepare("INSERT INTO ib_withdraw 
(email, trade_id, withdraw_amount, withdraw_type, company_bank, client_bank, account_holder_name, account_number, ifsc, type, random, Status, AdminRemark, transaction_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)");

$insert_stmt->bind_param(
    "ssdssssssssss",
    $request['email'],
    $request['trade_ids'],
    $request['total_commission'],
    $request['withdraw_type'],
    $request['company_bank'],
    $request['client_bank'],
    $request['account_holder_name'],
    $request['account_number'],
    $ifsc,
    $request['type'],
    $request['random'],
    $admin_remark,
    $transaction_id
);

$executed = $insert_stmt->execute();
$insert_stmt->close();

if ($executed) {
    // Update request status to approved
    $update_stmt = $conn->prepare("UPDATE ib_withdraw_request SET status=1, updated_at=NOW() WHERE id=?");
    $update_stmt->bind_param("i", $request_id);
    $update_stmt->execute();
    $update_stmt->close();

    // Deduct approved amount from ib_total_commission
    $update_commission_stmt = $conn->prepare("UPDATE ib_total_commission 
        SET available_commission = GREATEST(available_commission - ?, 0), updated_at = NOW() 
        WHERE ib_email = ?");
    $update_commission_stmt->bind_param("ds", $request['total_commission'], $request['email']);
    $update_commission_stmt->execute();
    $update_commission_stmt->close();

    echo json_encode([
        "success" => true,
        "message" => "Withdrawal approved and stored successfully",
        "transaction_id" => $transaction_id
    ], JSON_PRETTY_PRINT);
} else {
    echo json_encode(["success" => false, "message" => "Failed to approve withdrawal"]);
}
?>
