<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = [
    'success' => false,
    'message' => '',
    'min_payout_amount' => 10.00,
    'designation_title' => 'None',
    'is_kyc_verified' => false,
    'total_earnings' => 0.00,
    'total_withdrawn' => 0.00,
    'total_spent' => 0.00,
    'available_balance' => 0.00,
    'payouts_history' => [],
    'total_pages' => 1,
    'page' => 1
];

if (!isLoggedIn()) {
    $response['message'] = "Unauthorized.";
    echo json_encode($response);
    exit();
}

$currentUser = getCurrentUser();

// 1. Fetch designation payout criteria
try {
    $stmt_desig = $pdo->prepare("
        SELECT d.title, d.criteria_min_payout 
        FROM users u 
        LEFT JOIN designations d ON u.designation_id = d.id 
        WHERE u.id = ?
    ");
    $stmt_desig->execute([$currentUser['id']]);
    $desig_info = $stmt_desig->fetch();
    if ($desig_info && $desig_info['title']) {
        $response['designation_title'] = $desig_info['title'];
        $response['min_payout_amount'] = (float)$desig_info['criteria_min_payout'];
    }
} catch (PDOException $e) { }

// 2. Fetch KYC status
$isKycVerified = false;
$kycRecord = null;
try {
    $stmt_kyc = $pdo->prepare("SELECT * FROM kyc_records WHERE user_id = ?");
    $stmt_kyc->execute([$currentUser['id']]);
    $kycRecord = $stmt_kyc->fetch();
    if ($kycRecord && $kycRecord['doc1_status'] === 'approved' && $kycRecord['doc2_status'] === 'approved' && $kycRecord['bank_status'] === 'verified') {
        $isKycVerified = true;
    }
    $response['is_kyc_verified'] = $isKycVerified;
} catch (PDOException $e) { }

// 3. Compute balances
$total_earnings = 0.00;
$total_withdrawn = 0.00;
$available_balance = 0.00;
try {
    $stmt_earn = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE user_id = ?");
    $stmt_earn->execute([$currentUser['id']]);
    $total_earnings = (float)$stmt_earn->fetchColumn();

    // Actual bank withdrawals (excluding Wallet Event Payments)
    $stmt_pay_withdrawn = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM payouts WHERE user_id = ? AND status IN ('pending', 'paid') AND bank_name != 'Wallet Event Payment'");
    $stmt_pay_withdrawn->execute([$currentUser['id']]);
    $total_withdrawn = (float)$stmt_pay_withdrawn->fetchColumn();

    // Wallet event payments
    $stmt_pay_spent = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM payouts WHERE user_id = ? AND status = 'paid' AND bank_name = 'Wallet Event Payment'");
    $stmt_pay_spent->execute([$currentUser['id']]);
    $total_spent = (float)$stmt_pay_spent->fetchColumn();

    // Available balance calculation (must deduct all payouts: both bank withdrawals and event purchases)
    $stmt_pay_all = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM payouts WHERE user_id = ? AND status IN ('pending', 'paid')");
    $stmt_pay_all->execute([$currentUser['id']]);
    $total_payouts_all = (float)$stmt_pay_all->fetchColumn();

    $available_balance = max(0.00, $total_earnings - $total_payouts_all);
    
    $response['total_earnings'] = $total_earnings;
    $response['total_withdrawn'] = $total_withdrawn;
    $response['total_spent'] = $total_spent;
    $response['available_balance'] = $available_balance;
} catch (PDOException $e) { }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $response['message'] = "Security check failed (CSRF). Please try again.";
        echo json_encode($response);
        exit();
    }

    $amount = (float)($_POST['amount'] ?? 0.00);

    // Cooldown check: only 1 payout request per 24 hours (#11)
    try {
        $stmt_cooldown = $pdo->prepare("
            SELECT created_at FROM payouts 
            WHERE user_id = ? AND status = 'pending' 
            ORDER BY created_at DESC LIMIT 1
        ");
        $stmt_cooldown->execute([$currentUser['id']]);
        $last_pending = $stmt_cooldown->fetchColumn();
        if ($last_pending) {
            $last_time = strtotime($last_pending);
            $cooldown_hours = 24;
            if ((time() - $last_time) < ($cooldown_hours * 3600)) {
                $remaining = ceil(($cooldown_hours * 3600 - (time() - $last_time)) / 3600);
                $response['message'] = "You already have a pending payout request. Please wait approximately {$remaining} hour(s) before submitting another.";
                echo json_encode($response);
                exit();
            }
        }
    } catch (PDOException $e) { }

    $action = $_POST['action'] ?? '';
    if ($action === 'cancel') {
        $payoutId = (int)($_POST['payout_id'] ?? 0);
        if ($payoutId <= 0) {
            $response['message'] = "Invalid payout request ID.";
            echo json_encode($response);
            exit();
        }

        try {
            // Find and lock the pending payout record belonging to current user
            $stmt_check = $pdo->prepare("SELECT status FROM payouts WHERE id = ? AND user_id = ? FOR UPDATE");
            $stmt_check->execute([$payoutId, $currentUser['id']]);
            $payout_status = $stmt_check->fetchColumn();

            if ($payout_status === false) {
                $response['message'] = "Payout request not found.";
            } elseif ($payout_status !== 'pending') {
                $response['message'] = "Only pending payout requests can be cancelled.";
            } else {
                $stmt_upd = $pdo->prepare("UPDATE payouts SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt_upd->execute([$payoutId]);
                logAuditEvent('user_cancel_payout', 'payout', $payoutId, "User cancelled pending payout of user #" . $currentUser['id']);
                
                $response['success'] = true;
                $response['message'] = "Payout request cancelled successfully.";
            }
        } catch (PDOException $e) {
            error_log("Cancel payout error: " . $e->getMessage());
            $response['message'] = "Failed to cancel payout request. Please try again.";
        }
        echo json_encode($response);
        exit();
    }

    if (!$isKycVerified) {
        $response['message'] = "Withdrawal rejected: Your KYC documents must be approved and your bank account verified before requesting a payout.";
    } elseif ($amount <= 0.00) {
        $response['message'] = "Withdrawal rejected: Payout request amount must be greater than ₹0.00.";
    } elseif ($amount < $response['min_payout_amount']) {
        $response['message'] = "Withdrawal rejected: Payout amount is below your designation minimum limit of ₹" . number_format($response['min_payout_amount'], 2) . ".";
    } elseif ($amount > $available_balance) {
        $response['message'] = "Withdrawal rejected: Insufficient balance.";
    } else {
        try {
            $pdo->beginTransaction();
            
            $stmt_lock = $pdo->prepare("SELECT id FROM users WHERE id = ? FOR UPDATE");
            $stmt_lock->execute([$currentUser['id']]);
            
            $stmt_earn = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE user_id = ?");
            $stmt_earn->execute([$currentUser['id']]);
            $total_earnings_lock = (float)$stmt_earn->fetchColumn();

            $stmt_pay = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM payouts WHERE user_id = ? AND status IN ('pending', 'paid')");
            $stmt_pay->execute([$currentUser['id']]);
            $total_withdrawn_lock = (float)$stmt_pay->fetchColumn();

            $available_balance_lock = max(0.00, $total_earnings_lock - $total_withdrawn_lock);
            
            if ($amount > $available_balance_lock) {
                $response['message'] = "Withdrawal rejected: Insufficient balance.";
                $pdo->rollBack();
            } else {
                // Fetch settings to calculate TDS and platform fees
                $stmt_sett = $pdo->query("SELECT key, value FROM system_settings");
                $configs = $stmt_sett->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];

                $payout_fee_flat = (float)($configs['payout_platform_fee_flat'] ?? 0.00);
                $payout_fee_pct = (float)($configs['payout_platform_fee_percent'] ?? 0.00);
                $platform_fee = round($payout_fee_flat + ($amount * ($payout_fee_pct / 100)), 2);

                $has_pan = ($kycRecord && $kycRecord['doc2_status'] === 'approved');
                $tds_with_pan_pct = (float)($configs['payout_tds_with_pan'] ?? 5.00);
                $tds_without_pan_pct = (float)($configs['payout_tds_without_pan'] ?? 20.00);
                $tds_pct = $has_pan ? $tds_with_pan_pct : $tds_without_pan_pct;
                $tds_amount = round($amount * ($tds_pct / 100), 2);

                $net_amount = max(0.00, $amount - $platform_fee - $tds_amount);

                $stmt_ins = $pdo->prepare("
                    INSERT INTO payouts (user_id, amount, platform_fee, tds_amount, net_amount, status, bank_name, account_number) 
                    VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)
                ");
                $stmt_ins->execute([
                    $currentUser['id'],
                    $amount,
                    $platform_fee,
                    $tds_amount,
                    $net_amount,
                    $kycRecord['bank_name'] ?? 'N/A',
                    $kycRecord['account_number'] ?? 'N/A'
                ]);
                
                $pdo->commit();
                
                require_once __DIR__ . '/../../includes/notification_helper.php';
                sendMultichannelNotification($currentUser['id'], 'payout_status', [
                    'amount' => number_format($amount, 2),
                    'status' => 'Pending Review'
                ]);
                
                $response['success'] = true;
                $response['message'] = "Payout request of ₹" . number_format($amount, 2) . " submitted successfully.";
            }
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            error_log("Payout error: " . $e->getMessage());
            $response['message'] = "An unexpected error occurred. Please try again later.";
        }
    }
} else {
    // GET requests load history
    try {
        $limit = 10;
        $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
        $offset = ($page - 1) * $limit;

        $stmt_c = $pdo->prepare("SELECT COUNT(*) FROM payouts WHERE user_id = ?");
        $stmt_c->execute([$currentUser['id']]);
        $total_records = (int)$stmt_c->fetchColumn();
        $total_pages = ceil($total_records / $limit);

        $stmt_hist = $pdo->prepare("
            SELECT * FROM payouts 
            WHERE user_id = ? 
            ORDER BY id DESC 
            LIMIT ? OFFSET ?
        ");
        $stmt_hist->bindValue(1, $currentUser['id'], PDO::PARAM_INT);
        $stmt_hist->bindValue(2, $limit, PDO::PARAM_INT);
        $stmt_hist->bindValue(3, $offset, PDO::PARAM_INT);
        $stmt_hist->execute();
        
        $response['payouts_history'] = $stmt_hist->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $response['total_pages'] = max(1, $total_pages);
        $response['page'] = $page;
        $response['success'] = true;
    } catch (PDOException $e) {
        $response['message'] = "Failed to load payouts history.";
    }
}

echo json_encode($response);
