<?php
/**
 * Enfhess Marketplace - Premium Admin Hub Financial Ledger
 * Path: admin/transactions.php
 */

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

// Security Boundary Enforcement
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

// Global Currency Setup
$settings = $pdo->query("SELECT currency FROM general_settings WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$currency = $settings['currency'] ?? 'USD';

/**
 * 1. REAL-TIME FILTER LOGIC
 */
$filter = $_GET['filter'] ?? 'all';
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

$where = "WHERE payment_status = 'Paid'";
switch ($filter) {
    case 'today': $where .= " AND DATE(created_at) = CURDATE()"; break;
    case 'yesterday': $where .= " AND DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)"; break;
    case '7_days': $where .= " AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"; break;
    case 'this_month': $where .= " AND MONTH(created_at) = MONTH(NOW()) AND YEAR(created_at) = YEAR(NOW())"; break;
    case 'prev_month': $where .= " AND created_at >= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), '%Y-%m-01 00:00:00') AND created_at <= LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH))"; break;
    case 'custom':
        if (!empty($start_date) && !empty($end_date)) {
            $where .= " AND created_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59'";
        }
        break;
}

// Fetch Data
$stmt = $pdo->query("SELECT id, item_name, customer_name, price, payment_method, commission_type, commission_rate, net_seller_income, created_at FROM orders $where ORDER BY created_at DESC");
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Process Transactions
$allTransactions = [];
foreach ($orders as $order) {
    $gross = (float)$order['price'];
    $net = (float)$order['net_seller_income'];
    $comm = $gross - $net;
    $allTransactions[] = [
        'id' => $order['id'], 
        'date' => $order['created_at'], 
        'client' => $order['customer_name'],
        'item' => $order['item_name'], 
        'method' => strtoupper($order['payment_method']),
        'comm_type' => ($order['commission_type'] === 'percentage') ? $order['commission_rate'].'%' : format_currency($order['commission_rate']),
        'credit' => $gross, 
        'commission' => $comm, 
        'debit' => $net
    ];
}

// 2. PAGINATION ENGINE
$total_records = count($allTransactions);
$records_per_page = 15;
$ledgerCurrentPage = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($ledgerCurrentPage - 1) * $records_per_page;
$paginatedTransactions = array_slice($allTransactions, $offset, $records_per_page);
$total_pages = ceil($total_records / $records_per_page) ?: 1;

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

<body class="bg-nftDark text-white antialiased">
    <?php require_once __DIR__ . '/admin-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-10 pb-16 px-6">
        <h1 class="text-3xl font-black mb-1">Administrative Ledger</h1>
        <p class="text-nftTextGray text-sm mb-8">Auditing platform revenue and seller distributions.</p>

        <form method="GET" action="transactions.php" class="glass-card p-4 rounded-2xl mb-8 flex flex-wrap gap-4 items-center bg-slate-950/50 border border-slate-800">
            <select name="filter" onchange="this.form.submit()" class="bg-slate-900 border border-slate-800 rounded-lg px-3 py-2 text-xs cursor-pointer focus:border-nftAccentCyan outline-none">
                <option value="all" <?=($filter=='all')?'selected':''?>>All Time</option>
                <option value="today" <?=($filter=='today')?'selected':''?>>Today</option>
                <option value="yesterday" <?=($filter=='yesterday')?'selected':''?>>Yesterday</option>
                <option value="7_days" <?=($filter=='7_days')?'selected':''?>>Last 7 Days</option>
                <option value="this_month" <?=($filter=='this_month')?'selected':''?>>This Month</option>
                <option value="prev_month" <?=($filter=='prev_month')?'selected':''?>>Previous Month</option>
                <option value="custom" <?=($filter=='custom')?'selected':''?>>Custom Range</option>
            </select>
            
            <?php if($filter == 'custom'): ?>
                <input type="date" name="start_date" value="<?=$start_date?>" class="bg-slate-900 border border-slate-800 rounded-lg px-3 py-2 text-xs">
                <input type="date" name="end_date" value="<?=$end_date?>" class="bg-slate-900 border border-slate-800 rounded-lg px-3 py-2 text-xs">
                <button type="submit" class="bg-nftAccentCyan text-black font-bold px-4 py-2 rounded-lg text-xs hover:opacity-90">Apply</button>
            <?php endif; ?>
        </form>

        <div class="glass-card rounded-2xl border border-slate-800 bg-slate-950/50 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="bg-slate-900/50 text-[10px] uppercase tracking-widest text-slate-400">
                            <th class="p-4">Order ID</th>
                            <th class="p-4">Date</th>
                            <th class="p-4">Client / Item</th>
                            <th class="p-4">Method</th>
                            <th class="p-4 text-center">Commission</th>
                            <th class="p-4 text-right">Gross (Credit)</th>
                            <th class="p-4 text-right">Platform Fee</th>
                            <th class="p-4 text-right">Seller Net (Debit)</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-800 text-xs">
                        <?php foreach ($paginatedTransactions as $t): ?>
                        <tr class="hover:bg-slate-900/30">
                            <td class="p-4 font-mono text-nftAccentCyan">#<?= $t['id'] ?></td>
                            <td class="p-4"><?= date('M d, Y', strtotime($t['date'])) ?></td>
                            <td class="p-4">
                                <div class="font-bold"><?=$t['client']?></div>
                                <div class="text-[10px] text-slate-500"><?=$t['item']?></div>
                            </td>
                            <td class="p-4"><?=$t['method']?></td>
                            <td class="p-4 text-center font-bold text-slate-300"><?=$t['comm_type']?></td>
                            <td class="p-4 text-right text-emerald-400 font-mono">+<?=htmlspecialchars(format_currency($t['credit']), ENT_QUOTES, 'UTF-8')?></td>
                            <td class="p-4 text-right text-purple-400 font-mono"><?=htmlspecialchars(format_currency($t['commission']), ENT_QUOTES, 'UTF-8')?></td>
                            <td class="p-4 text-right text-rose-400 font-mono">-<?=htmlspecialchars(format_currency($t['debit']), ENT_QUOTES, 'UTF-8')?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="mt-6 flex justify-between items-center text-xs">
            <div class="text-slate-500">Page <?=htmlspecialchars((string)$ledgerCurrentPage, ENT_QUOTES, 'UTF-8')?> of <?=htmlspecialchars((string)$total_pages, ENT_QUOTES, 'UTF-8')?></div>
            <div class="space-x-2">
                <?php 
                $query_str = http_build_query(['filter'=>$filter, 'start_date'=>$start_date, 'end_date'=>$end_date]);
                $prevPage = max(1, $ledgerCurrentPage - 1);
                $nextPage = min($total_pages, $ledgerCurrentPage + 1);
                if($ledgerCurrentPage > 1): ?>
                    <a href="?<?=htmlspecialchars($query_str, ENT_QUOTES, 'UTF-8')?>&page=<?=htmlspecialchars((string)$prevPage, ENT_QUOTES, 'UTF-8')?>" class="px-4 py-2 bg-slate-900 rounded-lg hover:border-nftAccentCyan border border-slate-800">Previous</a>
                <?php endif; ?>
                <?php if($ledgerCurrentPage < $total_pages): ?>
                    <a href="?<?=htmlspecialchars($query_str, ENT_QUOTES, 'UTF-8')?>&page=<?=htmlspecialchars((string)$nextPage, ENT_QUOTES, 'UTF-8')?>" class="px-4 py-2 bg-slate-900 rounded-lg hover:border-nftAccentCyan border border-slate-800">Next</a>
                <?php endif; ?>
            </div>
        </div>
    </main>
</body>
