<?php
/**
 * Agentic Square - Premium Multi-Vendor Marketplace Core
 * Unified Financial Ledger Accounts, Audits & Dynamic Operations Engine
 * Path: seller/transactions.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;
}

// Global Logged-in User ID from Session Context
$logged_in_user_id = (int)$_SESSION['user_id'];

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

// 1. EXTRACT & COMPOSE UNIFIED TRANSACTION STREAM FROM THE DATABASE PIPELINES
$allTransactions = [];

// Pipeline A: Extract Paid Orders where orders.user_id matches the logged-in session user ID
$orderStmt = $pdo->prepare("
    SELECT id, item_name, price, commission_type, commission_rate, created_at 
    FROM orders 
    WHERE seller_id = ? 
    AND payment_status = 'Paid'
");
$orderStmt->execute([$logged_in_user_id]);
$orders = $orderStmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($orders as $order) {
    $gross_credit = (float)$order['price'];
    $comm_rate    = (float)$order['commission_rate'];
    $comm_type    = trim(strtolower($order['commission_type']));
    
    // Dynamic Debit Assessment Module mapping to type variation attributes
   if ($comm_type === 'percentage') {
    $calculated_debit = ($gross_credit * $comm_rate) / 100;
} else {
    $calculated_debit = $comm_rate; // fixed amount
}

$allTransactions[] = [
    'date'        => $order['created_at'],
    'timestamp'   => strtotime($order['created_at']),
    'description' => "Sale Earning: " . htmlspecialchars($order['item_name']) . " (Order # " . $order['id'] . ")",

    'credit'      => $gross_credit,
    'debit'       => $calculated_debit,
    'net_pool'    => $gross_credit - $calculated_debit
];

   
}

// Pipeline B: Extract Accepted Payout Settlements where withdrawal_requests.user_id matches the logged-in session user ID
$payoutStmt = $pdo->prepare("
    SELECT id, withdrawal_amount, accepted_at, withdrawal_method 
    FROM withdrawal_requests 
    WHERE user_id = ? AND LOWER(withdrawal_status) = 'accepted'
");
$payoutStmt->execute([$logged_in_user_id]);
$payouts = $payoutStmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($payouts as $payout) {
    // Structural Date Assignment Fallback Node Engine
    $payout_date = !empty($payout['accepted_at']) ? $payout['accepted_at'] : date('Y-m-d H:i:s');
    $payout_amount = (float)$payout['withdrawal_amount'];

    $allTransactions[] = [
        'date'        => $payout_date,
        'timestamp'   => strtotime($payout_date),
        'description' => "Fund Liquidation Settlement: Payout via " . htmlspecialchars($payout['withdrawal_method']) . " (Req #" . $payout['id'] . ")",
        'credit'      => 0.00,
        'debit'       => $payout_amount,
        'net_pool'    => -$payout_amount // Withdrawals pull down ledger pools directly
    ];
}

// 2. CHRONOLOGICAL LOG CONSOLIDATION & RUNNING BALANCE COMPILATION ENGINE
// Sort timeline records from oldest to newest to compute mathematical continuity balance fields accurately
usort($allTransactions, function ($a, $b) {
    return $a['timestamp'] <=> $b['timestamp'];
});

$running_balance = 0.00;
foreach ($allTransactions as $index => $transaction) {
    $running_balance += $transaction['net_pool'];
    $allTransactions[$index]['balance'] = $running_balance;
}

// Reverse array chronological sequence to surface modern nodes inside viewports first
$allTransactions = array_reverse($allTransactions);

// 3. SERVER-SIDE TIMEFRAME INTERACTION FILTER ROUTER
$selected_timeframe = $_GET['timeline'] ?? 'all';
$custom_start       = $_GET['start_date'] ?? '';
$custom_end         = $_GET['end_date'] ?? '';

if ($selected_timeframe !== 'all') {
    $start_bound_stamp = 0;
    $end_bound_stamp   = 2147483647; // Max standard 32-bit timestamp upper bounds limit

    if ($selected_timeframe === 'this_month') {
        $start_bound_stamp = mktime(0, 0, 0, (int)date('m'), 1, (int)date('Y'));
        $end_bound_stamp   = time();
    } elseif ($selected_timeframe === 'prev_month') {
        $start_bound_stamp = mktime(0, 0, 0, (int)date('m') - 1, 1, (int)date('Y'));
        $end_bound_stamp   = mktime(23, 59, 59, (int)date('m'), 0, (int)date('Y'));
    } elseif ($selected_timeframe === 'custom' && !empty($custom_start) && !empty($custom_end)) {
        $start_bound_stamp = strtotime($custom_start . ' 00:00:00');
        $end_bound_stamp   = strtotime($custom_end . ' 23:59:59');
    }

    $allTransactions = array_filter($allTransactions, function ($transaction) use ($start_bound_stamp, $end_bound_stamp) {
        return ($transaction['timestamp'] >= $start_bound_stamp && $transaction['timestamp'] <= $end_bound_stamp);
    });
}

// 4. SLIDING WINDOW PAGINATION CONTEXT MATRIX ENGINE
$total_records = count($allTransactions);
$records_per_page = 12;
$total_pages = (int)ceil($total_records / $records_per_page);
if ($total_pages < 1) $total_pages = 1;

$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($current_page < 1) $current_page = 1;
if ($current_page > $total_pages) $current_page = $total_pages;

$offset = ($current_page - 1) * $records_per_page;
$paginatedTransactions = array_slice($allTransactions, $offset, $records_per_page);

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__ . '/seller-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">Seller Console</a>
                <span>/</span>
                <span class="text-white">// Financial Statements Core</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">Accounting Ledger</h1>
                <p class="text-sm text-nftTextGray mt-1">Audit complete double-entry transaction histories tracking raw sales credits, commission adjustments, and cash withdrawals.</p>
            </div>

            <form method="GET" action="transactions.php" class="glass-card p-5 rounded-2xl border border-slate-800/80 grid grid-cols-1 md:grid-cols-4 gap-4 items-end bg-slate-950/40 backdrop-blur-md">
                <div class="space-y-1">
                    <label for="timelineFilterTrigger" class="block text-[10px] font-bold uppercase text-nftTextGray tracking-wider flex items-center gap-1.5">
                        <i class="fa-solid fa-calendar-days text-nftAccentCyan"></i> Historical Timeframe Filter
                    </label>
                    <select id="timelineFilterTrigger" name="timeline" 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" <?php echo $selected_timeframe === 'all' ? 'selected' : ''; ?>>Full Lifetime Ledger Logs</option>
                        <option value="this_month" <?php echo $selected_timeframe === 'this_month' ? 'selected' : ''; ?>>Current Calendar Month</option>
                        <option value="prev_month" <?php echo $selected_timeframe === 'prev_month' ? 'selected' : ''; ?>>Previous Calendar Month</option>
                        <option value="custom" <?php echo $selected_timeframe === 'custom' ? 'selected' : ''; ?>>Custom Date Range Selection</option>
                    </select>
                </div>

                <div id="customDateRangeBoxWrapper" class="<?php echo $selected_timeframe === 'custom' ? '' : '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 Date Lower Bound</label>
                        <input type="date" name="start_date" id="customDateLowerBoundary" value="<?php echo htmlspecialchars($custom_start); ?>" 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 Date Upper Bound</label>
                        <input type="date" name="end_date" id="customDateUpperBoundary" value="<?php echo htmlspecialchars($custom_end); ?>" 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>
                    <button type="submit" class="w-full py-2.5 rounded-xl bg-slate-900 border border-slate-800 text-xs font-bold tracking-wider text-white hover:text-nftAccentCyan hover:border-nftAccentCyan transition-all duration-150 flex items-center justify-center gap-2">
                        <i class="fa-solid fa-filter"></i> Synchronize Bounds
                    </button>
                </div>
            </form>

            <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">
                        <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">Date</th>
                                <th class="py-4 px-4">Operational Statement Narrative Ledger Mapping</th>
                                <th class="py-4 px-4 text-right">Debit</th>
                                <th class="py-4 px-4 text-right">Credit</th>
                                <th class="py-4 px-5 text-right">Balance</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-900/40 text-xs font-medium">
                            <?php if (count($paginatedTransactions) > 0): ?>
                                <?php 
                                $sl_counter = $offset + 1; 
                                foreach ($paginatedTransactions as $row): 
                                ?>
                                    <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_counter++; ?></td>
                                        
                                        <td class="py-4 px-4 font-sans text-slate-300 whitespace-nowrap">
                                            <?php echo date('M d, Y | h:i A', $row['timestamp']); ?>
                                        </td>
                                        
                                        <td class="py-4 px-4 font-sans text-white max-w-sm truncate" title="<?php echo $row['description']; ?>">
                                            <?php echo $row['description']; ?>
                                        </td>
                                        
                                        <td class="py-4 px-4 font-mono text-right font-bold text-rose-400">
                                            <?php echo $row['debit'] > 0 ? '- ' . htmlspecialchars(format_currency($row['debit']), ENT_QUOTES, 'UTF-8') : '<span class="text-slate-800 font-normal">-</span>'; ?>
                                        </td>
                                        
                                        <td class="py-4 px-4 font-mono text-right font-bold text-emerald-400">
                                            <?php echo $row['credit'] > 0 ? '+ ' . htmlspecialchars(format_currency($row['credit']), ENT_QUOTES, 'UTF-8') : '<span class="text-slate-800 font-normal">-</span>'; ?>
                                        </td>
                                        
                                        <td class="py-4 px-5 font-mono text-right font-black text-white bg-slate-900/10">
                                            <?php echo htmlspecialchars(format_currency($row['balance']), ENT_QUOTES, 'UTF-8'); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="py-16 text-center text-nftTextGray text-xs font-medium font-sans">
                                        <i class="fa-solid fa-list-check block text-2xl text-slate-800 mb-2"></i>
                                        No financial ledger records found mapping tracking coordinates to selected parameters.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($total_pages > 1): ?>
                    <div class="px-6 py-4 border-t border-slate-900/60 bg-slate-950/40 flex items-center justify-between">
                        <div class="text-xs text-nftTextGray font-semibold">
                            Showing ledger item records <span class="text-white"><?php echo $offset + 1; ?></span> to <span class="text-white"><?php echo min($offset + $records_per_page, $total_records); ?></span> of <span class="text-white"><?php echo $total_records; ?></span> entries.
                        </div>
                        <div class="flex items-center space-x-1.5">
                            
                            <?php if ($current_page > 1): ?>
                                <a href="?timeline=<?php echo $selected_timeframe; ?>&start_date=<?php echo urlencode($custom_start); ?>&end_date=<?php echo urlencode($custom_end); ?>&page=<?php echo $current_page - 1; ?>" class="px-3 py-1.5 rounded-lg bg-slate-900 border border-slate-800 hover:border-nftAccentCyan text-[11px] font-bold text-nftTextGray hover:text-white transition-all">
                                    Previous
                                </a>
                            <?php endif; ?>

                            <?php
                            $pagination_range_window = 3;
                            if ($total_pages <= $pagination_range_window + 2) {
                                for ($p = 1; $p <= $total_pages; $p++) {
                                    renderPaginationItemLink($p, $current_page, $selected_timeframe, $custom_start, $custom_end);
                                }
                            } else {
                                renderPaginationItemLink(1, $current_page, $selected_timeframe, $custom_start, $custom_end);

                                if ($current_page > 3) {
                                    echo '<span class="px-2 text-slate-600 font-bold text-xs select-none">...</span>';
                                }

                                $start_page_loop_index = max(2, $current_page - 1);
                                $end_page_loop_index   = min($total_pages - 1, $current_page + 1);

                                if ($current_page <= 2) {
                                    $end_page_loop_index = $pagination_range_window;
                                }
                                if ($current_page >= $total_pages - 1) {
                                    $start_page_loop_index = $total_pages - $pagination_range_window + 1;
                                }

                                for ($p = $start_page_loop_index; $p <= $end_page_loop_index; $p++) {
                                    renderPaginationItemLink($p, $current_page, $selected_timeframe, $custom_start, $custom_end);
                                }

                                if ($current_page < $total_pages - 2) {
                                    echo '<span class="px-2 text-slate-600 font-bold text-xs select-none">...</span>';
                                }

                                renderPaginationItemLink($total_pages, $current_page, $selected_timeframe, $custom_start, $custom_end);
                            }
                            ?>

                            <?php if ($current_page < $total_pages): ?>
                                <a href="?timeline=<?php echo $selected_timeframe; ?>&start_date=<?php echo urlencode($custom_start); ?>&end_date=<?php echo urlencode($custom_end); ?>&page=<?php echo $current_page + 1; ?>" class="px-3 py-1.5 rounded-lg bg-slate-900 border border-slate-800 hover:border-nftAccentCyan text-[11px] font-bold text-nftTextGray hover:text-white transition-all">
                                    Next
                                </a>
                            <?php endif; ?>

                        </div>
                    </div>
                <?php endif; ?>
            </div>

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

<?php 
/**
 * Helper Subroutine Outputting Uniform Pagination Link Blocks Context Layout Components
 */
function renderPaginationItemLink($pageNumber, $activePage, $timeframe, $start, $end) {
    $isActive = ($pageNumber === $activePage);
    $stylingClasses = $isActive 
        ? 'bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple text-white border-transparent' 
        : 'bg-slate-900 border-slate-800 text-nftTextGray hover:text-white hover:border-slate-700';
    
    echo sprintf(
        '<a href="?timeline=%s&start_date=%s&end_date=%s&page=%d" class="px-3 py-1.5 rounded-lg border text-[11px] font-mono font-bold transition-all %s">%d</a>',
        urlencode($timeframe),
        urlencode($start),
        urlencode($end),
        $pageNumber,
        $stylingClasses,
        $pageNumber
    );
}
?>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const filterSelect = document.getElementById('timelineFilterTrigger');
    const customBoundsBox = document.getElementById('customDateRangeBoxWrapper');

    if (filterSelect && customBoundsBox) {
        filterSelect.addEventListener('change', function () {
            if (this.value === 'custom') {
                customBoundsBox.classList.remove('hidden');
            } else {
                customBoundsBox.classList.add('hidden');
            }
        });
    }
});
</script>

</body>
</html>
