<?php
/**
 * Enfhess Marketplace - Premium Seller Hub Reports & Analytics Panel
 * Path: seller/reports.php
 */

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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

$seller_user_id = (int)$_SESSION['user_id'];

/**
 * ARCHITECTURAL TIME METRIC FILTERING PARSER
 */
$filter = isset($_GET['filter']) ? trim($_GET['filter']) : 'all';
$start_date = isset($_GET['start_date']) ? trim($_GET['start_date']) : '';
$end_date = isset($_GET['end_date']) ? trim($_GET['end_date']) : '';

$date_query_clause = "";
$bindings = [$seller_user_id];

// Explicit Date Boundary Calculation Match Blocks (Using 2026 Engine Benchmarks)
switch ($filter) {
    case 'this_month':
        $date_query_clause = " AND created_at >= DATE_FORMAT(NOW() ,'%Y-%m-01 00:00:00') ";
        break;
    case 'last_28_days':
        $date_query_clause = " AND created_at >= DATE_SUB(NOW(), INTERVAL 28 DAY) ";
        break;
    case 'previous_month':
        $date_query_clause = " 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)) {
            $date_query_clause = " AND created_at >= ? AND created_at <= ? ";
            $bindings[] = $start_date . " 00:00:00";
            $bindings[] = $end_date . " 23:59:59";
        }
        break;
    case 'all':
default:
        $date_query_clause = ""; // Fetch raw unbothered history variables
        break;
}

/**
 * CENTRALIZED SECURE DATA ENGINE ACQUISITION MATRICES
 */
try {
    // A. Always pull structural Real-Time Available Escrow Account Balances
    $sellerQuery = $pdo->prepare("SELECT current_balance FROM sellers WHERE user_id = ? LIMIT 1");
    $sellerQuery->execute([$seller_user_id]);
    $sellerProfile = $sellerQuery->fetch();
    $currentBalance = (float)($sellerProfile['current_balance'] ?? 0.00);

    // B. Collect marketplace platform fee policies
    $feeRules = $pdo->query("SELECT commission_type, commission_rate FROM general_settings WHERE id = 1 LIMIT 1")->fetch();
    $com_type = $feeRules['commission_type'] ?? 'percentage';
    $com_rate = (float)($feeRules['commission_rate'] ?? 0.00);

    // C. Execute Hydration Queries matching the active selected temporal timeframe context
    $ordersSql = "SELECT price, created_at FROM orders WHERE seller_id = ? AND payment_status = 'Paid' " . $date_query_clause . " ORDER BY created_at ASC";
    $ordersStmt = $pdo->prepare($ordersSql);
    $ordersStmt->execute($bindings);
    $filteredOrders = $ordersStmt->fetchAll();

    // D. Compute Core Analytical Variables Loops
    $totalSold = count($filteredOrders);
    $totalNetIncome = 0.00;
    
    // Chart Array Containers Structure
    $timelineDataPoints = [];

    foreach ($filteredOrders as $order) {
        $price = (float)$order['price'];
        $cut = ($com_type === 'percentage') ? ($price * $com_rate) / 100 : $com_rate;
        if ($cut > $price) $cut = $price;
        
        $net_profit = $price - $cut;
        $totalNetIncome += $net_profit;

        // Group timeline records dynamically by Day-Format for chart compilation maps
        $dayKey = date('Y-m-d', strtotime($order['created_at']));
        if (!isset($timelineDataPoints[$dayKey])) {
            $timelineDataPoints[$dayKey] = ['units' => 0, 'income' => 0.00];
        }
        $timelineDataPoints[$dayKey]['units']++;
        $timelineDataPoints[$dayKey]['income'] += $net_profit;
    }

} catch (\PDOException $e) {
    die("Data Analytics Component Compilation Exception: " . $e->getMessage());
}

// Inject layouts configurations properties
require_once __DIR__ . '/../sections/header.php';
?>

<body class="bg-nftDark text-white antialiased overflow-x-hidden">

    <?php include_once __DIR__ . '/seller-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-16 px-4 sm:px-6 lg:px-8">
        <div class="max-w-7xl mx-auto space-y-8">
            
            <div class="flex items-center justify-between flex-wrap gap-4 border-b border-slate-900/60 pb-6">
                <div>
                    <div class="flex items-center space-x-2 text-[10px] font-bold uppercase tracking-widest text-slate-500 mb-2">
                        <a href="seller-dashboard.php" class="hover:text-nftAccentCyan transition-colors">Workspace Workspace</a>
                        <span>/</span>
                        <span class="text-nftAccentPurple">Performance Metrics Intelligence</span>
                    </div>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">Reports & Marketplace Ledger</h1>
                    <p class="text-xs text-nftTextGray mt-1">Audit temporal sales logs, system fees breakdowns, and computational net capital charts arrays.</p>
                </div>

                <form method="GET" action="reports.php" id="analyticsFilterInterfaceControl" class="flex flex-wrap items-center gap-3 bg-slate-950/60 p-2.5 rounded-2xl border border-slate-900">
                    <div class="flex flex-col">
                        <select name="filter" onchange="toggleCustomDatePicker(this.value)" class="bg-slate-900 text-white font-bold text-xs px-3.5 py-2 rounded-xl border border-slate-800 focus:outline-none focus:border-nftAccentCyan transition-all cursor-pointer">
                            <option value="all" <?php echo ($filter === 'all') ? 'selected' : ''; ?>>All Historical Records</option>
                            <option value="this_month" <?php echo ($filter === 'this_month') ? 'selected' : ''; ?>>This Month</option>
                            <option value="last_28_days" <?php echo ($filter === 'last_28_days') ? 'selected' : ''; ?>>Last 28 Performance Days</option>
                            <option value="previous_month" <?php echo ($filter === 'previous_month') ? 'selected' : ''; ?>>Previous Closed Month</option>
                            <option value="custom" <?php echo ($filter === 'custom') ? 'selected' : ''; ?>>[Custom Date Range Matrix]</option>
                        </select>
                    </div>

                    <div id="custom_date_wrapper" class="<?php echo ($filter === 'custom') ? 'flex' : 'hidden'; ?> items-center gap-2 animate-fadeIn">
                        <input type="date" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>" class="bg-slate-900 text-white font-mono text-xs px-2.5 py-1.5 rounded-lg border border-slate-800 focus:outline-none">
                        <span class="text-slate-600 text-xs font-bold font-sans">to</span>
                        <input type="date" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>" class="bg-slate-900 text-white font-mono text-xs px-2.5 py-1.5 rounded-lg border border-slate-800 focus:outline-none">
                    </div>

                    <button type="submit" class="bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple hover:from-cyan-500 hover:to-purple-600 px-4 py-2 rounded-xl text-xs font-bold uppercase tracking-wider text-white shadow-md active:scale-95 transition-all">
                        <i class="fa-solid fa-filter mr-1"></i> Apply Sync
                    </button>
                </form>
            </div>

            <?php include_once __DIR__ . '/report-card.php'; ?>

            <?php include_once __DIR__ . '/report-chart.php'; ?>

        </div>
    </main>

    <script>
        function toggleCustomDatePicker(selectedValue) {
            const dateWrapper = document.getElementById('custom_date_wrapper');
            if (selectedValue === 'custom') {
                dateWrapper.classList.remove('hidden');
                dateWrapper.classList.add('flex');
            } else {
                dateWrapper.classList.remove('flex');
                dateWrapper.classList.add('hidden');
            }
        }
    </script>
</body>
</html>