<?php
/**
 * ============================================================================
 * admin/index.php - Admin Dashboard
 * ============================================================================
 */

// Include admin base (handles authentication & permissions)
require_once __DIR__ . '/includes/base.php';

// Define breadcrumbs
$breadcrumbs = [
    ['title' => 'Dashboard', 'url' => '']
];

// Fetch dashboard statistics
try {
    $sql = "SELECT 
                (SELECT COUNT(*) FROM users WHERE is_active = 1) as total_active_users,
                (SELECT COUNT(*) FROM users WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)) as new_users_month,
                (SELECT COUNT(*) FROM user_approvals WHERE approval_status = 'pending') as pending_approvals,
                (SELECT COUNT(*) FROM products WHERE status = 'available') as active_products,
                (SELECT COUNT(*) FROM orders WHERE status = 'pending') as pending_orders,
                (SELECT COUNT(*) FROM reports WHERE status = 'pending') as pending_reports";
    
    $stmt = $db->query($sql);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    logError('Dashboard stats error: ' . $e->getMessage());
    $stats = [
        'total_active_users' => 0,
        'new_users_month' => 0,
        'pending_approvals' => 0,
        'active_products' => 0,
        'pending_orders' => 0,
        'pending_reports' => 0
    ];
}

// Get recent activities
try {
    $sql = "SELECT 
                aal.id,
                aal.action_type,
                aal.action_description,
                aal.created_at,
                u.full_name as admin_name,
                ar.role_name as admin_role
            FROM admin_activity_log aal
            LEFT JOIN users u ON aal.admin_id = u.id
            LEFT JOIN admin_roles ar ON u.admin_role_id = ar.id
            ORDER BY aal.created_at DESC
            LIMIT 10";
    $stmt = $db->query($sql);
    $recentActivities = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    logError('Recent activities error: ' . $e->getMessage());
    $recentActivities = [];
}

// Start rendering
renderAdminHeader('Dashboard', $breadcrumbs);
?>

<!-- Page Content -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">Dashboard Overview</h2>
        <p class="text-muted mb-0">Welcome back, <?php echo htmlspecialchars($currentUserName); ?>!</p>
    </div>
    <div>
        <button class="btn btn-outline-secondary" onclick="location.reload()">
            <i class="bi bi-arrow-clockwise me-2"></i>Refresh
        </button>
    </div>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card stat-card shadow-sm border-0">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Active Users</p>
                        <h3 class="mb-0 fw-bold"><?php echo number_format($stats['total_active_users']); ?></h3>
                        <small class="text-success">
                            <i class="bi bi-arrow-up"></i> <?php echo $stats['new_users_month']; ?> this month
                        </small>
                    </div>
                    <div class="text-primary" style="font-size: 2.5rem;">
                        <i class="bi bi-people"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card stat-card shadow-sm border-0">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Pending Approvals</p>
                        <h3 class="mb-0 fw-bold"><?php echo $stats['pending_approvals']; ?></h3>
                        <?php if ($stats['pending_approvals'] > 0): ?>
                            <a href="<?php echo APP_URL; ?>/admin/approvals.php" class="btn btn-sm btn-warning mt-2">Review Now</a>
                        <?php endif; ?>
                    </div>
                    <div class="text-warning" style="font-size: 2.5rem;">
                        <i class="bi bi-hourglass-split"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card stat-card shadow-sm border-0">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Active Products</p>
                        <h3 class="mb-0 fw-bold"><?php echo number_format($stats['active_products']); ?></h3>
                    </div>
                    <div class="text-success" style="font-size: 2.5rem;">
                        <i class="bi bi-box-seam"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card stat-card shadow-sm border-0">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Pending Reports</p>
                        <h3 class="mb-0 fw-bold"><?php echo $stats['pending_reports']; ?></h3>
                        <?php if ($stats['pending_reports'] > 0): ?>
                            <a href="<?php echo APP_URL; ?>/admin/reports.php" class="btn btn-sm btn-danger mt-2">Review</a>
                        <?php endif; ?>
                    </div>
                    <div class="text-danger" style="font-size: 2.5rem;">
                        <i class="bi bi-flag"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recent Activity -->
<?php if (hasAdminPermission('view_logs')): ?>
<div class="card shadow-sm border-0 mb-4">
    <div class="card-header bg-white border-0 py-3 d-flex justify-content-between align-items-center">
        <h5 class="mb-0 fw-bold">
            <i class="bi bi-activity text-primary me-2"></i>Recent Admin Activity
        </h5>
        <a href="<?php echo APP_URL; ?>/admin/logs.php" class="btn btn-sm btn-outline-primary">View All Logs</a>
    </div>
    <div class="card-body p-0">
        <?php if (empty($recentActivities)): ?>
            <div class="text-center py-5 text-muted">
                <i class="bi bi-activity" style="font-size: 3rem;"></i>
                <p class="mb-0 mt-2">No recent activity</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Admin</th>
                            <th>Action</th>
                            <th>Description</th>
                            <th>Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recentActivities as $activity): ?>
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <img src="<?php echo getAvatarUrl(); ?>" class="rounded-circle me-2" width="32" height="32">
                                    <div>
                                        <div class="fw-semibold"><?php echo htmlspecialchars($activity['admin_name'] ?? 'Unknown'); ?></div>
                                        <small class="text-muted"><?php echo htmlspecialchars($activity['admin_role'] ?? 'Admin'); ?></small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="badge bg-primary"><?php echo htmlspecialchars($activity['action_type']); ?></span>
                            </td>
                            <td><?php echo htmlspecialchars(truncate($activity['action_description'] ?? '', 80)); ?></td>
                            <td>
                                <small class="text-muted"><?php echo timeAgo($activity['created_at']); ?></small>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<!-- Quick Links -->
<div class="row">
    <div class="col-md-4 mb-3">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <h6 class="card-title fw-bold">
                    <i class="bi bi-people text-primary me-2"></i>User Management
                </h6>
                <p class="card-text small text-muted">Manage users, approvals, and permissions</p>
                <div class="d-grid gap-2">
                    <?php if (hasAdminPermission('approve_users')): ?>
                        <a href="<?php echo APP_URL; ?>/admin/approvals.php" class="btn btn-sm btn-outline-primary">Approvals</a>
                    <?php endif; ?>
                    <?php if (hasAdminPermission('manage_users')): ?>
                        <a href="<?php echo APP_URL; ?>/admin/users.php" class="btn btn-sm btn-outline-primary">All Users</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-4 mb-3">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <h6 class="card-title fw-bold">
                    <i class="bi bi-box-seam text-success me-2"></i>Content Management
                </h6>
                <p class="card-text small text-muted">Manage products, prices, and tips</p>
                <div class="d-grid gap-2">
                    <?php if (hasAdminPermission('manage_products')): ?>
                        <a href="<?php echo APP_URL; ?>/admin/products.php" class="btn btn-sm btn-outline-success">Products</a>
                    <?php endif; ?>
                    <?php if (hasAdminPermission('manage_prices')): ?>
                        <a href="<?php echo APP_URL; ?>/admin/market-prices.php" class="btn btn-sm btn-outline-success">Market Prices</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-4 mb-3">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <h6 class="card-title fw-bold">
                    <i class="bi bi-gear text-secondary me-2"></i>System Settings
                </h6>
                <p class="card-text small text-muted">Configure system and settings</p>
                <div class="d-grid gap-2">
                    <?php if (hasAdminPermission('manage_locations')): ?>
                        <a href="<?php echo APP_URL; ?>/admin/locations.php" class="btn btn-sm btn-outline-secondary">Locations</a>
                    <?php endif; ?>
                    <?php if (hasAdminPermission('manage_settings')): ?>
                        <a href="<?php echo APP_URL; ?>/admin/settings.php" class="btn btn-sm btn-outline-secondary">Settings</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php renderAdminFooter(); ?>