<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once '../config.php';

if (!isset($_SESSION['affiliate_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit;
}

$affiliate_id = (int)$_SESSION['affiliate_id'];
$method = $_POST['method'] ?? 'bkash';

// Get current balance
$affiliate = $conn->query("SELECT balance FROM affiliates WHERE id = $affiliate_id")->fetch_assoc();

if ($affiliate['balance'] <= 0) {
    echo json_encode(['success' => false, 'message' => 'Insufficient balance']);
    exit;
}

$amount = $affiliate['balance'];
$conn->query("INSERT INTO affiliate_payouts (affiliate_id, amount, payment_method, status) 
              VALUES ($affiliate_id, $amount, '$method', 'pending')");

// Reset balance (payout requested)
$conn->query("UPDATE affiliates SET balance = 0 WHERE id = $affiliate_id");

echo json_encode(['success' => true]);