<?php
/**
 * Agentic Square - Premium Administrative Core
 * Central Operations Financial Settlement Control Engine
 * Path: admin/withdrawal.php
 */

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

/**
 * STRICT SECURITY AUDIT GUARD
 */
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$success_message = '';
$error_message   = '';

// 1. FETCH BASE CURRENCY SYSTEM PROPERTY
$settings = $pdo->query("SELECT currency FROM general_settings WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$currency = $settings['currency'] ?? 'USD';

// ------------------------------------------------------------------------
// ACTION ROUTER: Handle Administrative Status Mutator Submissions
// ------------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status_action'])) {
    $request_id    = (int)$_POST['request_id'];
    $target_status = isset($_POST['withdrawal_status']) ? trim($_POST['withdrawal_status']) : '';
    $admin_note    = isset($_POST['admin_note']) ? filter_var(trim($_POST['admin_note']), FILTER_SANITIZE_SPECIAL_CHARS) : '';

    // Guard Clause to check status verification rules mapping strings (Using 'Accepted')
    if ($request_id > 0 && in_array($target_status, ['Pending', 'Accepted', 'Rejected'])) {
        try {
            // Fetch target ledger entry data properties securely
            $reqStmt = $pdo->prepare("SELECT * FROM withdrawal_requests WHERE id = ? LIMIT 1");
            $reqStmt->execute([$request_id]);
            $requestData = $reqStmt->fetch(PDO::FETCH_ASSOC);

            if (!$requestData) {
                throw new Exception("Target payout request sequence reference could not be mapped within active tables.");
            }

            $current_ledger_status = $requestData['withdrawal_status'];
            $withdrawal_amount     = (float)$requestData['withdrawal_amount'];
            $request_user_id       = (int)$requestData['user_id']; 

            // Prevent repeated ledger balance deductions if already processed
            if ($current_ledger_status === 'Accepted') {
                throw new Exception("This financial layout item has already been authorized. Deductions are securely locked.");
            }

            // START ATOMIC DATABASE MUTATION TRANSACTION BLOCK
            $pdo->beginTransaction();

            if ($target_status === 'Accepted') {
                // Check if seller has sufficient clearable balance fields available
                $selCheckStmt = $pdo->prepare("SELECT current_balance FROM sellers WHERE user_id = ? LIMIT 1 FOR UPDATE");
                $selCheckStmt->execute([$request_user_id]);
                $sellerProfile = $selCheckStmt->fetch(PDO::FETCH_ASSOC);

                if (!$sellerProfile) {
                    throw new Exception("Operational Failure: Linked vendor asset mapping profile not found.");
                }

                $seller_balance = (float)$sellerProfile['current_balance'];

                if ($seller_balance < $withdrawal_amount) {
                    throw new Exception("Liquidation violation: Vendor account holds insufficient clearable balance nodes.");
                }

                // DEDUCT FUNDS FROM SELLER CURRENT_BALANCE
                $deductBalanceStmt = $pdo->prepare("UPDATE sellers SET current_balance = current_balance - :amount, updated_at = NOW() WHERE user_id = :uid");
                $deductBalanceStmt->execute([
                    'amount' => $withdrawal_amount,
                    'uid'    => $request_user_id
                ]);
            }

            // Secure current timestamp update to your accepted_at column
            $accepted_at_value = ($target_status === 'Accepted' || $target_status === 'Rejected') ? date('Y-m-d H:i:s') : null;
            
            $updateLedgerSql = "UPDATE withdrawal_requests SET 
                withdrawal_status = :status, 
                note = :note, 
                accepted_at = :accepted_at 
                WHERE id = :rid";
            
            $updateLedgerStmt = $pdo->prepare($updateLedgerSql);
            $updateLedgerStmt->execute([
                'status'      => $target_status,
                'note'        => $admin_note,
                'accepted_at' => $accepted_at_value,
                'rid'         => $request_id
            ]);

            // Commit all operational alterations securely
            $pdo->commit();
            $success_message = "Administrative settlement action updated and committed to financial history logs.";

        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error_message = $e->getMessage();
        }
    } else {
        $error_message = "Invalid configuration payload data. Verification state assignment tracking failed.";
    }
}

// 2. RETRIEVE ALL SYSTEM WITHDRAWAL REQUEST RECORDS
$querySql = "SELECT * FROM withdrawal_requests ORDER BY created_at DESC";
$allRequests = $pdo->query($querySql)->fetchAll(PDO::FETCH_ASSOC);

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

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

    <div class="flex-1 min-w-0 flex flex-col z-10 lg:pl-64">
        
        <main class="flex-1 py-10 px-4 sm:px-6 lg:px-8 max-w-[1600px] w-full mx-auto space-y-8 mt-14 lg:mt-0">
            
            <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">Admin Console</a>
                <span>/</span>
                <span class="text-white">// System Settlements</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">Global Payout Clearinghouse</h1>
                <p class="text-sm text-nftTextGray mt-1">Audit, authorize, or decline global vendor payout matrix distribution pipeline channels.</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 shadow-lg shadow-emerald-500/5">
                    <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 shadow-lg shadow-rose-500/5">
                    <i class="fa-solid fa-triangle-exclamation text-base"></i>
                    <span><?php echo $error_message; ?></span>
                </div>
            <?php endif; ?>

            <div class="glass-card rounded-2xl border border-slate-800/80 shadow-2xl overflow-hidden bg-slate-950/20 backdrop-blur-md">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse dynamic-table-layout">
                        <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">Creation Date</th>
                                <th class="py-4 px-4">Seller / Vendor Name</th>
                                <th class="py-4 px-4">Amount Requested</th>
                                <th class="py-4 px-4 text-center">Method Channel</th>
                                <th class="py-4 px-4">Endpoint Destination Info</th>
                                <th class="py-4 px-4 text-center">Status Flag</th>
                                <th class="py-4 px-4">Admin Internal Notes</th>
                                <th class="py-4 px-5 text-center">Action Node</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-900/40 text-xs font-medium">
                            <?php if (count($allRequests) > 0): ?>
                                <?php $sl = 1; foreach ($allRequests as $request): 
                                    $status = htmlspecialchars($request['withdrawal_status']);
                                    $statusClass = 'bg-amber-500/10 border-amber-500/20 text-amber-400';
                                    if ($status === 'Accepted') $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="border-b border-slate-900/20 hover:bg-slate-900/40 transition-colors duration-150">
                                        <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 whitespace-nowrap">
                                            <?php echo date('M d, Y | h:i A', strtotime($request['created_at'])); ?>
                                        </td>
                                        <td class="py-4 px-4 font-sans text-white">
                                            <div class="flex flex-col">
                                                <span class="font-bold"><?php echo htmlspecialchars($request['user_name']); ?></span>
                                                <span class="text-[10px] text-nftTextGray font-normal mt-0.5"><?php echo htmlspecialchars($request['user_email']); ?></span>
                                            </div>
                                        </td>
                                        <td class="py-4 px-4 font-mono font-bold text-white text-sm">
                                            <?php echo htmlspecialchars(format_currency($request['withdrawal_amount']), ENT_QUOTES, 'UTF-8'); ?>
                                        </td>
                                        <td class="py-4 px-4 text-center">
                                            <span class="px-2 py-1 rounded-md text-[11px] font-bold bg-slate-900 text-slate-300 border border-slate-800">
                                                <?php echo htmlspecialchars($request['withdrawal_method']); ?>
                                            </span>
                                        </td>
                                        <td class="py-4 px-4 font-sans text-slate-400 max-w-xs truncate" title="<?php echo htmlspecialchars($request['withdrawal_information']); ?>">
                                            <?php echo htmlspecialchars($request['withdrawal_information']); ?>
                                        </td>
                                        <td class="py-4 px-4 text-center">
                                            <span class="px-2.5 py-1 inline-block min-w-[85px] rounded-full text-[10px] font-bold uppercase tracking-wider border <?php echo $statusClass; ?>">
                                                <?php echo $status; ?>
                                            </span>
                                        </td>
                                        <td class="py-4 px-4 font-sans text-nftTextGray italic max-w-xs truncate" title="<?php echo !empty($request['note']) ? htmlspecialchars($request['note']) : ''; ?>">
                                            <?php echo !empty($request['note']) ? htmlspecialchars($request['note']) : '<span class="text-slate-700 font-normal not-italic">No operational remarks</span>'; ?>
                                        </td>
                                        <td class="py-4 px-5 text-center whitespace-nowrap">
                                            <?php if ($status === 'Pending'): ?>
                                                <button type="button" 
                                                        onclick="openStatusMutationModal(<?php echo htmlspecialchars(json_encode($request), ENT_QUOTES, 'UTF-8'); ?>)"
                                                        class="px-3 py-1.5 rounded-lg bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple hover:scale-[1.02] active:scale-[0.98] text-white text-[11px] font-bold tracking-wider transition-all shadow-md shadow-cyan-500/5">
                                                    Manage Request
                                                </button>
                                            <?php else: ?>
                                                <span class="text-[10px] font-bold uppercase tracking-widest text-slate-600 inline-flex items-center justify-center gap-1">
                                                    <i class="fa-solid fa-lock text-[9px]"></i> Settled
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="9" class="py-16 text-center text-nftTextGray text-xs font-sans">
                                        <i class="fa-solid fa-scale-balanced block text-3xl text-slate-800 mb-2"></i>
                                        No active ledger settlement allocation requests awaiting attention.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

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

<div id="financialSettlementModalOverlay" class="fixed inset-0 z-50 overflow-y-auto hidden bg-slate-950/80 backdrop-blur-sm items-center justify-center p-4 transition-all duration-300">
    <div class="glass-card w-full max-w-md rounded-2xl border border-slate-800/80 bg-slate-950/95 backdrop-blur-md shadow-2xl transform transition-all p-6 space-y-6">
        
        <div class="flex items-center justify-between border-b border-slate-900 pb-4">
            <h3 class="text-base font-bold text-white flex items-center gap-2">
                <i class="fa-solid fa-sliders text-nftAccentCyan text-sm"></i>
                <span>Resolve Liquidation Parameter</span>
            </h3>
            <button type="button" onclick="closeStatusMutationModal()" class="text-slate-500 hover:text-white transition-colors text-base p-1">
                <i class="fa-solid fa-xmark"></i>
            </button>
        </div>

        <form action="withdrawal.php" method="POST" class="space-y-4">
            <input type="hidden" id="modal_request_id_node" name="request_id" value="">

            <div class="bg-slate-950/80 rounded-xl p-4 border border-slate-900 space-y-2.5 shadow-inner">
                <div class="flex justify-between text-[11px] items-center">
                    <span class="text-nftTextGray font-bold uppercase tracking-wider">Vendor Link Account:</span>
                    <span id="modal_vendor_name_txt" class="text-white font-semibold tracking-wide"></span>
                </div>
                <div class="flex justify-between text-[11px] items-center">
                    <span class="text-nftTextGray font-bold uppercase tracking-wider">Total Request Payload:</span>
                    <span id="modal_allocation_amount_txt" class="text-amber-400 font-mono font-black text-sm"></span>
                </div>
            </div>

            <div class="space-y-1">
                <label for="withdrawal_status" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Authorization Output Strategy</label>
                <select id="withdrawal_status" name="withdrawal_status" 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 focus:ring-1 focus:ring-nftAccentCyan">
                    <option value="Pending">Leave Decision Node Pending</option>
                    <option value="Accepted">Accept & Pay Request (Deduct Balance)</option>
                    <option value="Rejected">Reject Request Allocation</option>
                </select>
            </div>

            <div class="space-y-1">
                <label for="admin_note" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Transaction Memo / Internal Note</label>
                <textarea id="admin_note" name="admin_note" rows="3" 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-slate-700 resize-none focus:ring-1 focus:ring-nftAccentCyan" placeholder="Provide tracking reference codes, verification tokens, or reason for system rejection..."></textarea>
            </div>

            <div class="flex items-center justify-end gap-3 pt-2">
                <button type="button" onclick="closeStatusMutationModal()" class="px-4 py-2.5 rounded-xl border border-slate-800 text-[11px] font-bold tracking-widest text-nftTextGray uppercase hover:bg-slate-900 hover:text-white transition-colors">
                    Cancel
                </button>
                <button type="submit" name="update_status_action" class="px-5 py-2.5 rounded-xl bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple font-bold text-[11px] tracking-widest text-white uppercase shadow-lg shadow-cyan-500/10 hover:shadow-cyan-500/20 transition-all">
                    Commit Changes
                </button>
            </div>
        </form>
    </div>
</div>

<script>
const modalOverlay     = document.getElementById('financialSettlementModalOverlay');
const idInputNode      = document.getElementById('modal_request_id_node');
const vendorNameSpan   = document.getElementById('modal_vendor_name_txt');
const amountValSpan    = document.getElementById('modal_allocation_amount_txt');
const statusSelectNode = document.getElementById('withdrawal_status');
const internalNoteArea = document.getElementById('admin_note');
const currencySymbol   = <?php echo json_encode(currency_symbol()); ?>;

function openStatusMutationModal(requestObject) {
    if (!requestObject) return;

    // Load form field targets
    idInputNode.value        = requestObject.id;
    vendorNameSpan.innerText = requestObject.user_name;
    
    const floatAmount = parseFloat(requestObject.withdrawal_amount).toFixed(2);
    amountValSpan.innerText  = `${currencySymbol}${floatAmount}`;
    
    statusSelectNode.value   = requestObject.withdrawal_status;
    internalNoteArea.value   = requestObject.note || '';

    // Open modal layer safely utilizing layout architecture alignments
    modalOverlay.classList.remove('hidden');
    modalOverlay.classList.add('flex');
    document.body.style.overflow = 'hidden';
}

function closeStatusMutationModal() {
    modalOverlay.classList.add('hidden');
    modalOverlay.classList.remove('flex');
    document.body.style.overflow = '';
}

window.addEventListener('click', function (e) {
    if (e.target === modalOverlay) {
        closeStatusMutationModal();
    }
});
</script>

</body>
</html>
