<?php
/**
 * Agentic Square - Premium Multi-Vendor Marketplace Core
 * Automated Asset Liquidation Ledger & Payout Gateway Interface
 * Path: seller/withdraw-funds.php
 */

require_once __DIR__ . '/../config/config.php';

// Enforce Active Session Guard
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'seller') {
    header('Location: ../login.php');
    exit;
}

$seller_id = (int)$_SESSION['user_id'];
$success_message = '';
$error_message   = '';

// 1. Fetch Hydrated Master Configuration Limits & Assets
$settings = $pdo->query("SELECT currency, min_withdrawal_amount FROM general_settings WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$currency = $settings['currency'] ?? 'USD';
$min_withdrawal_limit = (float)($settings['min_withdrawal_amount'] ?? 10.00);

// 2. Resolve Active Seller Accounts Base Meta Values Mapping
$userStmt = $pdo->prepare("SELECT full_name, email FROM users WHERE id = ? LIMIT 1");
$userStmt->execute([$seller_id]);
$currentUser = $userStmt->fetch(PDO::FETCH_ASSOC);

$user_name  = $currentUser['full_name'] ?? 'Vendor Node';
$user_email = $currentUser['email'] ?? '';

// 3. Process Outbound Liquidation Allocation Requests Post Payload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_withdrawal'])) {
    $requested_amount = filter_var($_POST['withdrawal_amount'] ?? 0, FILTER_VALIDATE_FLOAT);
    $withdrawal_method = in_array($_POST['withdrawal_method'] ?? '', ['PayPal', 'Bank']) ? $_POST['withdrawal_method'] : '';
    
    // Construct payment criteria matrices cleanly mapping to target string fields
    $withdrawal_info = '';
    if ($withdrawal_method === 'PayPal') {
        $paypal_email = filter_var(trim($_POST['paypal_email'] ?? ''), FILTER_DEFAULT);
        $withdrawal_info = "PayPal Account Email: " . filter_var($paypal_email, FILTER_SANITIZE_SPECIAL_CHARS);
    } elseif ($withdrawal_method === 'Bank') {
        $bank_name = filter_var(trim($_POST['bank_name'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
        $acc_name  = filter_var(trim($_POST['account_name'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
        $acc_num   = filter_var(trim($_POST['account_number'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
        $routing   = filter_var(trim($_POST['routing_number'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
        
        $withdrawal_info = "Bank Name: {$bank_name} | Acc Name: {$acc_name} | Acc #: {$acc_num} | Routing: {$routing}";
    }

    // Server-Side Constraint Threshold Verification Guards
    if ($requested_amount === false || $requested_amount < $min_withdrawal_limit) {
        $error_message = "Liquidation operational failure. The required transaction limit per action node is minimum " . format_currency($min_withdrawal_limit);
    } elseif (empty($withdrawal_method) || empty($withdrawal_info)) {
        $error_message = "Execution configuration parameter missing. Please supply appropriate payout endpoint routing metrics.";
    } else {
        try {
            // MATCHING YOUR UNIQUE COLUMN NAMES: user_id, user_name, user_email, withdrawal_amount, withdrawal_status, withdrawal_method, withdrawal_information, created_at
            $insert_sql = "INSERT INTO withdrawal_requests 
                (user_id, user_name, user_email, withdrawal_amount, withdrawal_status, withdrawal_method, withdrawal_information, created_at) 
                VALUES (:uid, :uname, :uemail, :amount, 'Pending', :method, :info, NOW())";
            
            $insStmt = $pdo->prepare($insert_sql);
            $insStmt->execute([
                'uid'     => $seller_id,
                'uname'   => $user_name,
                'uemail'  => $user_email,
                'amount'  => $requested_amount,
                'method'  => $withdrawal_method,
                'info'    => $withdrawal_info
            ]);
            
            $success_message = "Your payout request nodes have been serialized into the pending execution block successfully.";
        } catch (\PDOException $e) {
            $error_message = "Transactional database mutation error exception: " . $e->getMessage();
        }
    }
}

// 4. Extract Historical Ledger Data Stream Blocks for Table Render Mapping (Mapped to withdrawal_requests table)
$historyStmt = $pdo->prepare("SELECT * FROM withdrawal_requests WHERE user_id = ? ORDER BY created_at DESC");
$historyStmt->execute([$seller_id]);
$payoutHistory = $historyStmt->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../sections/header.php';
?>

<div class="min-h-screen bg-nftDark text-white antialiased flex">
    
    <?php require_once __DIR__ . '/seller-sidebar.php'; ?>

    <main class="flex-1 min-h-screen pt-24 lg:pt-10 pb-12 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto w-full transition-all duration-300">
        <div class="space-y-8">
            
            <div class="flex items-center space-x-2 text-xs text-nftTextGray uppercase tracking-widest font-bold">
                <a href="dashboard.php" class="hover:text-nftAccentCyan transition-colors">Seller Console</a>
                <span>/</span>
                <span class="text-white">// Balance Settlement</span>
            </div>

            <div class="border-b border-slate-900/60 pb-6">
                <h1 class="text-3xl font-extrabold tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-white via-white to-nftAccentCyan">Withdraw Platform Funds</h1>
                <p class="text-sm text-nftTextGray mt-1">Convert account balance fields into native revenue proceeds sent directly to financial endpoints.</p>
            </div>

            <?php if (!empty($success_message)): ?>
                <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 p-4 rounded-xl text-sm flex items-center space-x-2">
                    <i class="fa-solid fa-circle-check text-base"></i>
                    <span><?php echo $success_message; ?></span>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($error_message)): ?>
                <div class="bg-rose-500/10 border border-rose-500/20 text-rose-400 p-4 rounded-xl text-sm flex items-center space-x-2">
                    <i class="fa-solid fa-triangle-exclamation text-base"></i>
                    <span><?php echo $error_message; ?></span>
                </div>
            <?php endif; ?>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
                
                <div class="lg:col-span-1 glass-card p-6 rounded-2xl border border-slate-800/80 space-y-6">
                    <div>
                        <h2 class="text-base font-bold text-nftAccentCyan flex items-center space-x-2">
                            <i class="fa-solid fa-money-check-dollar text-sm"></i>
                            <span>Allocation Request Form</span>
                        </h2>
                        <p class="text-xs text-nftTextGray mt-1">Submit invoice records for active platform processing execution pools.</p>
                    </div>

                    <div class="p-4 bg-slate-950/80 border border-slate-900 rounded-xl flex items-center justify-between">
                        <span class="text-xs font-bold text-nftTextGray uppercase tracking-wider">Required Minimum Limit:</span>
                        <span class="text-sm font-black font-mono text-amber-400 bg-amber-500/10 px-2.5 py-1 rounded-lg border border-amber-500/20">
                            <?php echo htmlspecialchars(format_currency($min_withdrawal_limit), ENT_QUOTES, 'UTF-8'); ?>
                        </span>
                    </div>

                    <form action="withdraw-funds.php" method="POST" class="space-y-4">
                        
                        <div class="space-y-1">
                            <label for="withdrawal_amount" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Liquidation Face Amount</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-slate-500 font-mono text-sm font-semibold">
                                    <?php echo $currency; ?>
                                </span>
                                <input type="number" step="0.01" min="<?php echo $min_withdrawal_limit; ?>" id="withdrawal_amount" name="withdrawal_amount" required class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl pl-14 pr-4 py-3 text-sm text-white font-mono focus:outline-none transition-all" placeholder="0.00">
                            </div>
                        </div>

                        <div class="space-y-1">
                            <label for="withdrawal_method" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Disbursement Target Route</label>
                            <select id="withdrawal_method" name="withdrawal_method" required class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all cursor-pointer">
                                <option value="" disabled selected>Select execution channel...</option>
                                <option value="PayPal">PayPal Processing Gateway</option>
                                <option value="Bank">Direct Institutional Wire Transfer</option>
                            </select>
                        </div>

                        <div id="paypalFormSubSection" class="hidden dynamic-input-block-node space-y-1 animation-fade-in">
                            <label for="paypal_email" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Target PayPal Account Email Address</label>
                            <input type="email" id="paypal_email" name="paypal_email" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all" placeholder="name@domain.com">
                        </div>

                        <div id="bankFormSubSection" class="hidden dynamic-input-block-node space-y-3 animation-fade-in border-t border-slate-900/60 pt-4">
                            <div class="space-y-1">
                                <label class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Corporate Bank Entity Name</label>
                                <input type="text" name="bank_name" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all" placeholder="e.g. JPMorgan Chase">
                            </div>
                            <div class="space-y-1">
                                <label class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Account Holder Legal Name</label>
                                <input type="text" name="account_name" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all" placeholder="e.g. Shah M Polash">
                            </div>
                            <div class="space-y-1">
                                <label class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Account Base Routing ID / IBAN Code</label>
                                <input type="text" name="account_number" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all" placeholder="e.g. 123456789012">
                            </div>
                            <div class="space-y-1">
                                <label class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Transit Routing ABA / SWIFT Code Reference</label>
                                <input type="text" name="routing_number" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all" placeholder="e.g. 021000021">
                            </div>
                        </div>

                        <button type="submit" name="submit_withdrawal" class="w-full mt-2 py-3 rounded-xl bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple font-bold text-xs tracking-widest text-white uppercase shadow-lg shadow-cyan-500/10 hover:shadow-cyan-500/20 transition-all">
                            Dispatch Payout Pipeline Request
                        </button>
                    </form>
                </div>

                <div class="lg:col-span-2 space-y-4">
                    
                    <div class="glass-card p-5 rounded-2xl border border-slate-800/80 grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
                        <div class="space-y-1">
                            <label class="block text-[10px] font-bold uppercase text-nftTextGray tracking-wider flex items-center gap-1.5">
                                <i class="fa-solid fa-filter text-nftAccentCyan"></i> Historical Timeframe Filter
                            </label>
                            <select id="ledgerTimelineFilterTrigger" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2.5 text-xs text-white font-semibold focus:outline-none focus:border-nftAccentCyan transition-all cursor-pointer">
                                <option value="all">Full Lifetime Audits</option>
                                <option value="this_month">Current Calendar Month</option>
                                <option value="prev_month">Previous Calendar Month</option>
                                <option value="custom">Custom Date Range</option>
                            </select>
                        </div>

                        <div id="customDateRangeBoxWrapper" class="hidden md:col-span-2 grid grid-cols-2 gap-3 transition-all duration-300">
                            <div class="space-y-1">
                                <label class="block text-[10px] font-bold uppercase text-nftTextGray tracking-wider">Start Lower Boundary</label>
                                <input type="date" id="customDateLowerBoundary" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-nftAccentCyan transition-all">
                            </div>
                            <div class="space-y-1">
                                <label class="block text-[10px] font-bold uppercase text-nftTextGray tracking-wider">End Upper Boundary</label>
                                <input type="date" id="customDateUpperBoundary" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-nftAccentCyan transition-all">
                            </div>
                        </div>
                    </div>

                    <div class="glass-card rounded-2xl border border-slate-800/80 shadow-2xl overflow-hidden">
                        <div class="overflow-x-auto">
                            <table id="withdrawalLogDynamicMatrixTable" class="w-full text-left border-collapse">
                                <thead>
                                    <tr class="bg-slate-950/60 border-b border-slate-900 text-nftTextGray font-bold uppercase tracking-wider text-[10px]">
                                        <th class="py-4 px-5 text-center">SL</th>
                                        <th class="py-4 px-4">Request Log Timestamp</th>
                                        <th class="py-4 px-4">Face Amount</th>
                                        <th class="py-4 px-4">Method</th>
                                        <th class="py-4 px-4">Endpoint Destination Routing (Method ID)</th>
                                        <th class="py-4 px-5 text-center">Status Flag</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-slate-900/40 text-xs font-medium">
                                    <?php if (count($payoutHistory) > 0): ?>
                                        <?php $sl = 1; foreach ($payoutHistory as $logRow): 
                                            $status = htmlspecialchars($logRow['withdrawal_status']);
                                            $statusClass = 'bg-amber-500/10 border-amber-500/20 text-amber-400';
                                            if ($status === 'Approved') $statusClass = 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400';
                                            if ($status === 'Rejected') $statusClass = 'bg-rose-500/10 border-rose-500/20 text-rose-400';
                                        ?>
                                            <tr class="table-data-row-node border-b border-slate-900/20 hover:bg-slate-900/10 transition-colors" data-timestamp="<?php echo strtotime($logRow['created_at']); ?>">
                                                <td class="py-4 px-5 text-center font-mono text-slate-500"><?php echo $sl++; ?></td>
                                                <td class="py-4 px-4 font-sans text-slate-300">
                                                    <?php echo date('M d, Y | h:i A', strtotime($logRow['created_at'])); ?>
                                                </td>
                                                <td class="py-4 px-4 font-mono font-bold text-white">
                                                    <?php echo htmlspecialchars(format_currency($logRow['withdrawal_amount']), ENT_QUOTES, 'UTF-8'); ?>
                                                </td>
                                                <td class="py-4 px-4">
                                                    <span class="px-2 py-1 rounded-md text-[11px] font-bold bg-slate-800 text-slate-300 border border-slate-700/60">
                                                        <?php echo htmlspecialchars($logRow['withdrawal_method']); ?>
                                                    </span>
                                                </td>
                                                <td class="py-4 px-4 font-sans text-nftTextGray max-w-xs truncate" title="<?php echo htmlspecialchars($logRow['withdrawal_information']); ?>">
                                                    <?php echo htmlspecialchars($logRow['withdrawal_information']); ?>
                                                </td>
                                                <td class="py-4 px-5 text-center">
                                                    <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider border <?php echo $statusClass; ?>">
                                                        <?php echo $status; ?>
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr id="emptyLedgerFallbackFallbackRow">
                                            <td colspan="6" class="py-12 text-center text-nftTextGray text-xs font-medium font-sans">
                                                <i class="fa-solid fa-folder-open block text-2xl text-slate-800 mb-2"></i>
                                                No execution ledger payout entries synchronized tracking to this vendor index parameter.
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                </div>

            </div>
        </div>
    </main>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    
    // --- PART 1: DYNAMIC OPTION INPUT SWITCH ROUTER ---
    const routeSelector = document.getElementById('withdrawal_method');
    const paypalSection = document.getElementById('paypalFormSubSection');
    const bankSection   = document.getElementById('bankFormSubSection');

    if (routeSelector) {
        routeSelector.addEventListener('change', function () {
            toggleSubInputsVisibility(false, paypalSection);
            toggleSubInputsVisibility(false, bankSection);

            if (this.value === 'PayPal') {
                toggleSubInputsVisibility(true, paypalSection);
            } else if (this.value === 'Bank') {
                toggleSubInputsVisibility(true, bankSection);
            }
        });
    }

    function toggleSubInputsVisibility(show, elementBlock) {
        if (!elementBlock) return;
        const inputs = elementBlock.querySelectorAll('input');
        if (show) {
            elementBlock.classList.remove('hidden');
            inputs.forEach(input => { input.required = true; });
        } else {
            elementBlock.classList.add('hidden');
            inputs.forEach(input => { input.required = false; input.value = ''; });
        }
    }

    // --- PART 2: HIGH-PERFORMANCE REALTIME CLIENT GRID ROW TIMEFRAME CALCULATOR FILTER ENGINE ---
    const timelineTrigger = document.getElementById('ledgerTimelineFilterTrigger');
    const customBoundsBox = document.getElementById('customDateRangeBoxWrapper');
    const lowerBoundDate  = document.getElementById('customDateLowerBoundary');
    const upperBoundDate  = document.getElementById('customDateUpperBoundary');
    const tableRows       = document.querySelectorAll('.table-data-row-node');

    if (timelineTrigger) {
        timelineTrigger.addEventListener('change', function () {
            if (this.value === 'custom') {
                customBoundsBox.classList.remove('hidden');
            } else {
                customBoundsBox.classList.add('hidden');
                executeTimelineCalculations(this.value);
            }
        });
    }

    if (lowerBoundDate && upperBoundDate) {
        [lowerBoundDate, upperBoundDate].forEach(dateNode => {
            dateNode.addEventListener('input', () => {
                executeTimelineCalculations('custom');
            });
        });
    }

    function executeTimelineCalculations(mode) {
        const structuralNow = new Date();
        let targetStartUnixTimestamp = 0;
        let targetEndUnixTimestamp   = Infinity;

        if (mode === 'this_month') {
            const startOfMonth = new Date(structuralNow.getFullYear(), structuralNow.getMonth(), 1, 0, 0, 0, 0);
            targetStartUnixTimestamp = Math.floor(startOfMonth.getTime() / 1000);
        } else if (mode === 'prev_month') {
            const startOfPrevMonth = new Date(structuralNow.getFullYear(), structuralNow.getMonth() - 1, 1, 0, 0, 0, 0);
            const endOfPrevMonth   = new Date(structuralNow.getFullYear(), structuralNow.getMonth(), 0, 23, 59, 59, 999);
            targetStartUnixTimestamp = Math.floor(startOfPrevMonth.getTime() / 1000);
            targetEndUnixTimestamp   = Math.floor(endOfPrevMonth.getTime() / 1000);
        } else if (mode === 'custom') {
            const lowDateValue = lowerBoundDate.value ? new Date(lowerBoundDate.value + 'T00:00:00') : null;
            const highDateValue = upperBoundDate.value ? new Date(upperBoundDate.value + 'T23:59:59') : null;
            
            if (lowDateValue) targetStartUnixTimestamp = Math.floor(lowDateValue.getTime() / 1000);
            if (highDateValue) targetEndUnixTimestamp = Math.floor(highDateValue.getTime() / 1000);
        }

        tableRows.forEach(row => {
            const rowUnix = parseInt(row.getAttribute('data-timestamp'), 10);
            if (rowUnix >= targetStartUnixTimestamp && rowUnix <= targetEndUnixTimestamp) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }
});
</script>

</body>
</html>
