<?php
/**
 * ADMIN DASHBOARD PAGE - ENHANCED WITH DARKER COLORFUL CARDS
 * File: admin/index.php
 * UPDATED: Darker gradients for better text visibility
 */

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

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

// Initialize models
$walletTransactionModel = new WalletTransaction();
$withdrawalModel = new Withdrawal();
$vendorModel = new Vendor();
$customerModel = new Customer();

$page_title = "Admin Dashboard";
$active_menu = "dashboard";

$db = Database::getInstance();

$db = Database::getInstance();

// ================================================================
// CALCULATE ORDER STATISTICS CORRECTLY
// ================================================================

$today = date('Y-m-d');

// Total Orders
$total_orders_result = $db->fetch("SELECT COUNT(*) as count FROM orders");
$total_orders = $total_orders_result ? intval($total_orders_result['count']) : 0;

// Ongoing Orders - FIXED LOGIC
$ongoing_orders_result = $db->fetch("
    SELECT COUNT(*) as count 
    FROM orders 
    WHERE start_date <= ? 
    AND end_date >= ? 
    AND status NOT IN ('cancelled', 'completed')
", [$today, $today]);
$ongoing_orders = $ongoing_orders_result ? intval($ongoing_orders_result['count']) : 0;

// Future Orders - NEW
$future_orders_result = $db->fetch("
    SELECT COUNT(*) as count 
    FROM orders 
    WHERE start_date > ? 
    AND status NOT IN ('cancelled', 'completed')
", [$today]);
$future_orders = $future_orders_result ? intval($future_orders_result['count']) : 0;

// Completed Orders
$completed_orders_result = $db->fetch("SELECT COUNT(*) as count FROM orders WHERE status = 'completed'");
$completed_orders = $completed_orders_result ? intval($completed_orders_result['count']) : 0;

// Cancelled Orders
$cancelled_orders_result = $db->fetch("SELECT COUNT(*) as count FROM orders WHERE status = 'cancelled'");
$cancelled_orders = $cancelled_orders_result ? intval($cancelled_orders_result['count']) : 0;

// ================================================================
// GET WALLET STATISTICS USING WalletStats
// ================================================================
$walletStats = new WalletStats();
$admin_cards = $walletStats->getAdminWalletCards();

// Merge with our custom order stats
$admin_cards = array_merge([
    'available_balance' => 0.00,
    'total_earned' => 0.00,
    'total_withdrawn' => 0.00,
    'current_rent' => 0.00,
    'pending_rent' => 0.00,
    'current_security' => 0.00,
    'current_rent_onhold' => 0.00,
    'vendors_earning_onhold' => 0.00,
    'total_customers_spent' => 0.00,
    'total_vendors_earning' => 0.00,
    'total_customers' => 0,
    'total_vendors' => 0,
    'customers_wallet_balance' => 0.00,
    'vendors_wallet_balance' => 0.00,
    'total_orders' => $total_orders,
    // 'active_orders' => $ongoing_orders,
    'ongoing_orders' => $ongoing_orders,
    'future_orders' => $future_orders,
    'completed_orders' => $completed_orders,
    'cancelled_orders' => $cancelled_orders,
    'total_revenue' => 0.00,
    'total_refunded' => 0.00,
    'total_cancellation_penalty' => 0.00,
    'total_withdrawals' => 0.00,
    'pending_withdrawals' => 0.00,
    'orders_last_30_days' => 0,
    'revenue_last_30_days' => 0.00
], $admin_cards);


// Get user counts
$vendor_count = (int)$vendorModel->count();
$customer_count = (int)$customerModel->count();

// Get recent transactions
$recent_transactions = $walletTransactionModel->getRecent(10);
if (!is_array($recent_transactions)) {
    $recent_transactions = [];
}

// Get pending withdrawals
$pending_withdrawals = $withdrawalModel->getPending(5);
if (!is_array($pending_withdrawals)) {
    $pending_withdrawals = [];
}

// Get recent orders
$recent_orders_sql = "SELECT o.*, 
                      i.title as item_title,
                      CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                      v.business_name as vendor_name
                      FROM orders o
                      LEFT JOIN items i ON o.item_id = i.id
                      LEFT JOIN customers c ON o.customer_id = c.id
                      LEFT JOIN vendors v ON o.vendor_id = v.id
                      ORDER BY o.created_at DESC
                      LIMIT 5";
$recent_orders = $db->fetchAll($recent_orders_sql);
if (!is_array($recent_orders)) {
    $recent_orders = [];
}

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

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>

<style>
.hover-lift {
    transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
    cursor: pointer;
}
.hover-lift:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.3) !important;
}
a.card-link {
    text-decoration: none !important;
    color: inherit;
}
</style>

<div class="container-fluid">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <h1 class="h3 mb-0">📊 Dashboard Overview</h1>
            <p class="text-muted">Platform analytics and insights</p>
        </div>
    </div>

    <!-- ============================================================
         ADMIN WALLET CARDS - ROW 1 (Top Priority Metrics)
         DARKER GRADIENTS FOR BETTER VISIBILITY
         ============================================================ -->
    <div class="row mb-4">
        <!-- Total Revenue (Deep Purple) -->
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card text-white shadow-sm" style="background: linear-gradient(135deg, #7f00ff 0%, #e100ff 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="mb-2 fw-bold">💰 Total Revenue</h6>
                            <h2 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['total_revenue'], 2); ?></h2>
                            <small>All time</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">💎</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Total Customers Spent (Deep Pink) -->
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="card-transactions.php?filter=total_customers_spent" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #d53369 0%, #daae51 100%);">
                <div class="card-body">
                    <h6 class="mb-2 fw-bold">👥 Total Customers Spent</h6>
                    <h3 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['total_customers_spent'], 2); ?></h3>
                    <small>Lifetime</small>
                </div>
            </div>
            </a>
        </div>

        <!-- Card 3: Current Rent Onhold (Deep Orange) -->
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="card-transactions.php?filter=current_rent_onhold" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="mb-2 fw-bold">⏳ Current Rent Onhold</h6>
                            <h2 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['current_rent_onhold'], 2); ?></h2>
                            <small>Active orders</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">🔄</div>
                    </div>
                </div>
            </div>
            </a>
        </div>

        <!-- Current Security (Deep Gray/Blue) -->
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="card-transactions.php?filter=current_security" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #606c88 0%, #3f4c6b 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="mb-2 fw-bold">🔒 Current Security Onhold</h6>
                            <h2 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['current_security'], 2); ?></h2>
                            <small>Deposits</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">🛡️</div>
                    </div>
                </div>
            </div>
            </a>
        </div>

        <!-- Card 1: Available Commission (Deep Purple) -->
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="card-transactions.php?filter=available_commission" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="mb-2 fw-bold">💰 Available Commission</h6>
                            <h2 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['available_balance'], 2); ?></h2>
                            <small>Withdrawable</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">💵</div>
                    </div>
                </div>
            </div>
            </a>
        </div>

        <!-- Card 2: Total Commission (Deep Blue) -->
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="card-transactions.php?filter=total_commission_earned" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #2575fc 0%, #6a11cb 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="mb-2 fw-bold">📈 Total Commission Earned</h6>
                            <h2 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['total_earned'], 2); ?></h2>
                            <small>All time</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">📊</div>
                    </div>
                </div>
            </div>
            </a>
        </div>

        <!-- Total Vendors Earned (Deep Cyan) -->
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="card-transactions.php?filter=total_vendors_earned" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #06beb6 0%, #48b1bf 100%);">
                <div class="card-body">
                    <h6 class="mb-2 fw-bold">🏪 Total Vendors Earned</h6>
                    <h3 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['total_vendors_earning'], 2); ?></h3>
                    <small>Lifetime</small>
                </div>
            </div>
            </a>
        </div>

        <!-- Vendor Earnings Onhold (Deep Blue/Purple) -->
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="card-transactions.php?filter=vendor_earnings_onhold" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #2E3192 0%, #1BFFFF 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="mb-2 fw-bold">⏸️ Vendors Earnings Onhold</h6>
                            <h2 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['vendors_earning_onhold'], 2); ?></h2>
                            <small>Pending release</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">⏳</div>
                    </div>
                </div>
            </div>
            </a>
        </div>

    </div>

    <!-- ============================================================
         ORDER STATISTICS - ROW 2 (Darker Colorful Order Metrics)
         ============================================================ -->
    <div class="row mb-4">
        <!-- Total Orders (Deep Indigo) -->
        <div class="col-xl col-md-6 mb-3">
            <a href="orders.php?filter=all" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #5f72bd 0%, #9b23ea 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="mb-2 fw-bold">📦 Total Orders</h6>
                            <h2 class="mb-0 fw-bold"><?php echo number_format($admin_cards['total_orders']); ?></h2>
                            <small>All time</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">📋</div>
                    </div>
            </a>
        </div>
            </div>
        </div>

        <!-- Ongoing Orders (Deep Green) - FIXED! -->
        <div class="col-xl col-md-6 mb-3">
            <a href="orders.php?filter=ongoing" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="mb-2 fw-bold">🔄 Ongoing Orders</h6>
                            <h2 class="mb-0 fw-bold"><?php echo number_format($admin_cards['ongoing_orders']); ?></h2>
                            <small>Active now</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">⚡</div>
                    </div>
            </a>
        </div>
            </div>
        </div>

        <!-- Future Orders (Deep Blue) - NEW! -->
        <div class="col-xl col-md-6 mb-3">
            <a href="orders.php?filter=future" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="mb-2 fw-bold">🔮 Future Orders</h6>
                            <h2 class="mb-0 fw-bold"><?php echo number_format($admin_cards['future_orders']); ?></h2>
                            <small>Upcoming</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">📅</div>
                    </div>
            </a>
        </div>
            </div>
        </div>

        <!-- Completed Orders (Deep Orange) -->
        <div class="col-xl col-md-6 mb-3">
            <a href="orders.php?filter=completed" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="mb-2 fw-bold">✅ Completed Orders</h6>
                            <h2 class="mb-0 fw-bold"><?php echo number_format($admin_cards['completed_orders']); ?></h2>
                            <small>Finished</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">🎉</div>
                    </div>
            </a>
        </div>
            </div>
        </div>

        <!-- Cancelled Orders (Deep Red) -->
        <div class="col-xl col-md-6 mb-3">
            <a href="orders.php?filter=cancelled" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="mb-2 fw-bold">❌ Cancelled Orders</h6>
                            <h2 class="mb-0 fw-bold"><?php echo number_format($admin_cards['cancelled_orders']); ?></h2>
                            <small>All time</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">🚫</div>
                    </div>
            </a>
        </div>
            </div>
        </div>

        <!-- Total Users (Deep Magenta) -->
        <div class="col-xl col-md-6 mb-3">
            <div class="card text-white shadow-sm" style="background: linear-gradient(135deg, #c71d6f 0%, #d09693 100%);">
                <div class="card-body">
                    <h6 class="mb-2 fw-bold">👤 Total Users</h6>
                    <h3 class="mb-0 fw-bold"><?php echo number_format($vendor_count + $customer_count); ?></h3>
                    <small><?php echo $customer_count; ?> customers, <?php echo $vendor_count; ?> vendors</small>
                </div>
            </div>
        </div>

    </div>

    <!-- ============================================================
         FINANCIAL METRICS - ROW 3 (Darker Revenue & Refunds)
         ============================================================ -->
    <div class="row mb-4">
        
        <!-- Total Cancelled Refunds (Deep Coral) -->
        <div class="col-xl col-md-6 mb-3">
            <a href="card-transactions.php?filter=total_cancellation_refund" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #fc6076 0%, #ff9a44 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="mb-2 fw-bold">↩️ Total Cancelled</h6>
                            <h2 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['total_refunded'], 2); ?></h2>
                            <small>Refunds issued</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">💸</div>
                    </div>
                </div>
            </div>
            </a>
        </div>

        <!-- Cancelled Penalty -->
        <div class="col-xl col-md-6 mb-3">
            <a href="card-transactions.php?filter=total_cancellation_penalty" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #c7d156 0%, #b87d49 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="mb-2 fw-bold">↩️ Cancelled Penalty</h6>
                            <h2 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['total_cancellation_penalty'], 2); ?></h2>
                            <small>Penalty Charged</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">💸</div>
                    </div>
                </div>
            </div>
            </a>
        </div>

        <!-- Card 4: Total Withdrawn (Deep Teal) -->
        <div class="col-xl col-md-6 mb-3">
            <a href="card-transactions.php?filter=total_withdrawn" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="mb-2 fw-bold">💸 Total Withdrawn</h6>
                            <h2 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['total_withdrawals'], 2); ?></h2>
                            <small>Completed</small>
                        </div>
                        <div style="font-size: 48px; opacity: 0.3;">💳</div>
                    </div>
                </div>
            </div>
            </a>
        </div>

        <!-- Pending Withdrawals (Deep Amber) -->
        <div class="col-xl col-md-6 mb-3">
            <a href="card-transactions.php?filter=pending_withdrawals" class="card-link">
            <div class="card text-white shadow-sm hover-lift" style="background: linear-gradient(135deg, #f12711 0%, #f5af19 100%);">
                <div class="card-body">
                    <h6 class="mb-2 fw-bold">⏳ Pending Withdrawals</h6>
                    <h3 class="mb-0 fw-bold">₦<?php echo number_format($admin_cards['pending_withdrawals'], 2); ?></h3>
                    <small>Awaiting approval</small>
                </div>
            </div>
            </a>
        </div>

    </div>

    
    <!-- Recent Orders Table -->
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="mb-0">Recent Orders</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Order #</th>
                                    <th>Customer</th>
                                    <th>Item</th>
                                    <th>Vendor</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($recent_orders)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center text-muted py-4">No orders yet</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($recent_orders as $order): ?>
                                        <tr>
                                            <td>
                                                <a href="order-details.php?id=<?= $order['id'] ?>"><?= htmlspecialchars($order['order_number']) ?></a>
                                            </td>
                                            <td><?= htmlspecialchars($order['customer_name']) ?></td>
                                            <td><?= htmlspecialchars($order['item_title']) ?></td>
                                            <td><?= htmlspecialchars($order['vendor_name']) ?></td>
                                            <td>₦<?= number_format($order['total_amount'], 2) ?></td>
                                            <td>
                                                <?php
                                                $badge_class = 'secondary';
                                                switch($order['status']) {
                                                    case 'completed': $badge_class = 'success'; break;
                                                    case 'ongoing': $badge_class = 'primary'; break;
                                                    case 'confirmed': $badge_class = 'info'; break;
                                                    case 'cancelled': $badge_class = 'danger'; break;
                                                    case 'pending': $badge_class = 'warning'; break;
                                                }
                                                ?>
                                                <span class="badge bg-<?= $badge_class ?>"><?= ucfirst($order['status']) ?></span>
                                            </td>
                                            <td><?= date('M d, Y', strtotime($order['created_at'])) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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