<?php
/**
 * ADMIN FINANCE MANAGEMENT PAGE
 * File: admin/finance.php
 * View platform revenue, commissions, and financial analytics
 */

require_once '../app/Core/init.php';

// Require admin authentication
Auth::requireAdmin();

// Initialize models
$db = Database::getInstance();

// Get date range filter
$date_from = $_GET['date_from'] ?? date('Y-m-01'); // First day of current month
$date_to = $_GET['date_to'] ?? date('Y-m-d'); // Today
$period = $_GET['period'] ?? 'custom';

// Set date range based on period
switch ($period) {
    case 'today':
        $date_from = $date_to = date('Y-m-d');
        break;
    case 'yesterday':
        $date_from = $date_to = date('Y-m-d', strtotime('-1 day'));
        break;
    case 'this_week':
        $date_from = date('Y-m-d', strtotime('monday this week'));
        $date_to = date('Y-m-d');
        break;
    case 'last_week':
        $date_from = date('Y-m-d', strtotime('monday last week'));
        $date_to = date('Y-m-d', strtotime('sunday last week'));
        break;
    case 'this_month':
        $date_from = date('Y-m-01');
        $date_to = date('Y-m-d');
        break;
    case 'last_month':
        $date_from = date('Y-m-01', strtotime('first day of last month'));
        $date_to = date('Y-m-t', strtotime('last day of last month'));
        break;
    case 'this_year':
        $date_from = date('Y-01-01');
        $date_to = date('Y-m-d');
        break;
}

// Get total revenue (all paid orders)
$revenue_sql = "SELECT 
                COUNT(*) as total_orders,
                SUM(total_amount) as total_revenue,
                SUM(platform_fee) as total_platform_fee,
                SUM(subtotal) as total_subtotal
                FROM orders 
                WHERE payment_status = 'paid'
                AND DATE(created_at) BETWEEN ? AND ?";
$revenue = $db->fetch($revenue_sql, [$date_from, $date_to]);

// Get commission breakdown
$commission_sql = "SELECT 
                   COUNT(*) as total_commissions,
                   SUM(commission_amount) as total_earned,
                   SUM(CASE WHEN status = 'paid' THEN commission_amount ELSE 0 END) as paid_commission,
                   SUM(CASE WHEN status = 'pending' THEN commission_amount ELSE 0 END) as pending_commission
                   FROM commissions 
                   WHERE DATE(created_at) BETWEEN ? AND ?";
$commission = $db->fetch($commission_sql, [$date_from, $date_to]);

// Get vendor payouts
$vendor_payout_sql = "SELECT 
                      SUM(vendor_amount) as total_vendor_payout
                      FROM commissions 
                      WHERE status = 'paid'
                      AND DATE(created_at) BETWEEN ? AND ?";
$vendor_payout = $db->fetch($vendor_payout_sql, [$date_from, $date_to]);

// Get payment gateway breakdown
$gateway_sql = "SELECT 
                payment_gateway,
                COUNT(*) as total_transactions,
                SUM(amount) as total_amount
                FROM payments 
                WHERE status = 'completed'
                AND DATE(created_at) BETWEEN ? AND ?
                GROUP BY payment_gateway";
$gateways = $db->fetchAll($gateway_sql, [$date_from, $date_to]);

// Get top performing vendors
$top_vendors_sql = "SELECT 
                    v.business_name,
                    v.id,
                    COUNT(o.id) as total_orders,
                    SUM(o.total_amount) as total_sales,
                    SUM(c.commission_amount) as platform_earnings
                    FROM vendors v
                    LEFT JOIN orders o ON v.id = o.vendor_id AND o.payment_status = 'paid'
                    LEFT JOIN commissions c ON o.id = c.order_id
                    WHERE DATE(o.created_at) BETWEEN ? AND ?
                    GROUP BY v.id
                    ORDER BY total_sales DESC
                    LIMIT 10";
$top_vendors = $db->fetchAll($top_vendors_sql, [$date_from, $date_to]);

// Get recent transactions
$transactions_sql = "SELECT 
                     t.*, 
                     u.email,
                     CASE 
                         WHEN u.user_type = 'vendor' THEN v.business_name
                         WHEN u.user_type = 'customer' THEN CONCAT(c.first_name, ' ', c.last_name)
                         ELSE u.email
                     END as user_name
                     FROM transactions t
                     LEFT JOIN wallets w ON t.wallet_id = w.id
                     LEFT JOIN users u ON w.user_id = u.id
                     LEFT JOIN vendors v ON u.id = v.user_id
                     LEFT JOIN customers c ON u.id = c.user_id
                     WHERE DATE(t.created_at) BETWEEN ? AND ?
                     ORDER BY t.created_at DESC
                     LIMIT 20";
$recent_transactions = $db->fetchAll($transactions_sql, [$date_from, $date_to]);

// Get daily revenue chart data (last 30 days)
$chart_sql = "SELECT 
              DATE(created_at) as date,
              COUNT(*) as orders,
              SUM(total_amount) as revenue,
              SUM(platform_fee) as commission
              FROM orders 
              WHERE payment_status = 'paid'
              AND DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
              GROUP BY DATE(created_at)
              ORDER BY date ASC";
$chart_data = $db->fetchAll($chart_sql);

// Page variables
$page_title = "Finance & Analytics";
$active_menu = "finance";

// Include header
include '../templates/layouts/admin/head.php';
?>

<div class="main-content">

    <?php include '../templates/layouts/admin/header.php'; ?>

    <div class="page-header">
        <div class="header-left">
            <h1><i class="fas fa-chart-line"></i> Finance & Analytics</h1>
            <p class="text-muted">Platform revenue and financial insights</p>
        </div>
        <div class="header-right">
            <button class="btn btn-success" onclick="exportFinanceReport()">
                <i class="fas fa-download"></i> Export Report
            </button>
        </div>
    </div>

    <!-- Content -->
    <div class="content">

    <!-- Date Filter -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label">Quick Period</label>
                    <select name="period" class="form-control" onchange="this.form.submit()">
                        <option value="custom" <?= $period === 'custom' ? 'selected' : '' ?>>Custom Range</option>
                        <option value="today" <?= $period === 'today' ? 'selected' : '' ?>>Today</option>
                        <option value="yesterday" <?= $period === 'yesterday' ? 'selected' : '' ?>>Yesterday</option>
                        <option value="this_week" <?= $period === 'this_week' ? 'selected' : '' ?>>This Week</option>
                        <option value="last_week" <?= $period === 'last_week' ? 'selected' : '' ?>>Last Week</option>
                        <option value="this_month" <?= $period === 'this_month' ? 'selected' : '' ?>>This Month</option>
                        <option value="last_month" <?= $period === 'last_month' ? 'selected' : '' ?>>Last Month</option>
                        <option value="this_year" <?= $period === 'this_year' ? 'selected' : '' ?>>This Year</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Date From</label>
                    <input type="date" name="date_from" class="form-control" value="<?= $date_from ?>" <?= $period !== 'custom' ? 'disabled' : '' ?>>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Date To</label>
                    <input type="date" name="date_to" class="form-control" value="<?= $date_to ?>" <?= $period !== 'custom' ? 'disabled' : '' ?>>
                </div>
                <div class="col-md-3">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i> Apply Filter
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Revenue Overview -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-gradient-primary text-white">
                <div class="card-body">
                    <h6 class="text-white-50 mb-2">Total Revenue</h6>
                    <h2 class="mb-0"><?= format_money($revenue['total_revenue'] ?? 0) ?></h2>
                    <small><?= number_format($revenue['total_orders'] ?? 0) ?> paid orders</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-gradient-success text-white">
                <div class="card-body">
                    <h6 class="text-white-50 mb-2">Platform Commission</h6>
                    <h2 class="mb-0"><?= format_money($commission['total_earned'] ?? 0) ?></h2>
                    <small><?= number_format($commission['total_commissions'] ?? 0) ?> commissions</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-gradient-info text-white">
                <div class="card-body">
                    <h6 class="text-white-50 mb-2">Vendor Payouts</h6>
                    <h2 class="mb-0"><?= format_money($vendor_payout['total_vendor_payout'] ?? 0) ?></h2>
                    <small>Paid to vendors</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-gradient-warning text-white">
                <div class="card-body">
                    <h6 class="text-white-50 mb-2">Pending Commission</h6>
                    <h2 class="mb-0"><?= format_money($commission['pending_commission'] ?? 0) ?></h2>
                    <small>Awaiting settlement</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Revenue Chart -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-chart-area"></i> Revenue Trend (Last 30 Days)</h5>
        </div>
        <div class="card-body">
            <canvas id="revenueChart" height="80"></canvas>
        </div>
    </div>

    <div class="row">
        <!-- Payment Gateways -->
        <div class="col-md-6 mb-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-credit-card"></i> Payment Gateways</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($gateways)): ?>
                        <p class="text-muted text-center py-3">No payment data for this period</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-sm mb-0">
                                <thead>
                                    <tr>
                                        <th>Gateway</th>
                                        <th class="text-center">Transactions</th>
                                        <th class="text-end">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($gateways as $gateway): ?>
                                        <tr>
                                            <td>
                                                <strong><?= ucfirst($gateway['payment_gateway']) ?></strong>
                                            </td>
                                            <td class="text-center">
                                                <span class="badge bg-secondary"><?= number_format($gateway['total_transactions']) ?></span>
                                            </td>
                                            <td class="text-end">
                                                <strong><?= format_money($gateway['total_amount']) ?></strong>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Top Vendors -->
        <div class="col-md-6 mb-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-trophy"></i> Top Performing Vendors</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($top_vendors)): ?>
                        <p class="text-muted text-center py-3">No vendor data for this period</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-sm mb-0">
                                <thead>
                                    <tr>
                                        <th>Vendor</th>
                                        <th class="text-center">Orders</th>
                                        <th class="text-end">Sales</th>
                                        <th class="text-end">Our Earnings</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($top_vendors as $index => $vendor): ?>
                                        <tr>
                                            <td>
                                                <span class="badge bg-secondary me-1">#<?= $index + 1 ?></span>
                                                <strong><?= esc($vendor['business_name']) ?></strong>
                                            </td>
                                            <td class="text-center"><?= number_format($vendor['total_orders']) ?></td>
                                            <td class="text-end"><?= format_money($vendor['total_sales']) ?></td>
                                            <td class="text-end text-success">
                                                <strong><?= format_money($vendor['platform_earnings']) ?></strong>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Transactions -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-exchange-alt"></i> Recent Transactions</h5>
        </div>
        <div class="card-body p-0">
            <?php if (empty($recent_transactions)): ?>
                <div class="empty-state py-5">
                    <i class="fas fa-exchange-alt fa-3x text-muted mb-3"></i>
                    <p class="text-muted">No transactions found for this period</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Reference</th>
                                <th>User</th>
                                <th>Type</th>
                                <th>Category</th>
                                <th>Amount</th>
                                <th>Balance After</th>
                                <th>Date</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_transactions as $trans): ?>
                                <tr>
                                    <td><code><?= esc($trans['reference']) ?></code></td>
                                    <td>
                                        <strong><?= esc($trans['user_name']) ?></strong><br>
                                        <small class="text-muted"><?= esc($trans['email']) ?></small>
                                    </td>
                                    <td>
                                        <?php if ($trans['transaction_type'] === 'credit'): ?>
                                            <span class="badge bg-success">Credit</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger">Debit</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= ucfirst(str_replace('_', ' ', $trans['category'])) ?></td>
                                    <td>
                                        <strong class="<?= $trans['transaction_type'] === 'credit' ? 'text-success' : 'text-danger' ?>">
                                            <?= $trans['transaction_type'] === 'credit' ? '+' : '-' ?>
                                            <?= format_money($trans['amount']) ?>
                                        </strong>
                                    </td>
                                    <td><?= format_money($trans['balance_after']) ?></td>
                                    <td>
                                        <small><?= format_date($trans['created_at'], 'M d, Y h:i A') ?></small>
                                    </td>
                                    <td><?= format_status_badge($trans['status']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
.bg-gradient-primary {
    background: linear-gradient(135deg, #007bff 0%, #6610f2 100%);
}
.bg-gradient-success {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
}
.bg-gradient-info {
    background: linear-gradient(135deg, #17a2b8 0%, #007bff 100%);
}
.bg-gradient-warning {
    background: linear-gradient(135deg, #ffc107 0%, #ff6b6b 100%);
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Revenue Chart
const chartData = <?= json_encode($chart_data) ?>;
const ctx = document.getElementById('revenueChart').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: chartData.map(d => d.date),
        datasets: [{
            label: 'Revenue',
            data: chartData.map(d => d.revenue),
            borderColor: '#28a745',
            backgroundColor: 'rgba(40, 167, 69, 0.1)',
            tension: 0.4,
            fill: true
        }, {
            label: 'Commission',
            data: chartData.map(d => d.commission),
            borderColor: '#007bff',
            backgroundColor: 'rgba(0, 123, 255, 0.1)',
            tension: 0.4,
            fill: true
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: true,
        plugins: {
            legend: {
                position: 'top'
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return '₦' + value.toLocaleString();
                    }
                }
            }
        }
    }
});

function exportFinanceReport() {
    const params = new URLSearchParams(window.location.search);
    params.set('export', 'pdf');
    window.location.href = 'finance-export.php?' + params.toString();
}
</script>

<?php include '../templates/layouts/admin/footer.php'; ?>