<?php
/**
 * ============================================================================
 * admin/includes/base.php - Admin Base Layout & Access Control (FIXED)
 * Handles admin authentication, permissions, and common layout
 * ============================================================================
 */

// Define admin access
if (!defined('AIMS_ACCESS')) {
    define('AIMS_ACCESS', true);
}

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

// Check if user is logged in
if (!isLoggedIn()) {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

// Get user details
$currentUserId = getUserId();
$currentUserType = getUserType();
$currentUserName = getUserName();

// Check admin access
if (!hasAdminAccess()) {
    setFlashMessage('Access denied. Admin privileges required.', 'error');
    header('Location: ' . APP_URL . '/dashboard/');
    exit();
}

// Initialize database
$database = new Database();
$db = $database->getConnection();

// Get admin role and permissions
$adminRole = getAdminRole($currentUserId, $db);
$permissions = getAdminPermissions($adminRole, $db);

// Define page permissions
$pagePermissions = [
    'index.php' => ['view_dashboard'],
    'approvals.php' => ['manage_users', 'approve_users'],
    'approval-details.php' => ['manage_users', 'approve_users'],
    'users.php' => ['manage_users'],
    'admins.php' => ['manage_users'],
    'locations.php' => ['manage_locations'],
    'products.php' => ['manage_products'],
    'orders.php' => ['view_orders'],
    'market-prices.php' => ['manage_prices'],
    'tips.php' => ['manage_content'],
    'reports.php' => ['manage_reports'],
    'settings.php' => ['manage_settings'],
    'logs.php' => ['view_logs'],
    'analytics.php' => ['view_analytics'],
    'roles.php' => ['manage_roles']
];

// Check page-specific permissions
$currentPage = basename($_SERVER['PHP_SELF']);
if (isset($pagePermissions[$currentPage])) {
    $requiredPerms = $pagePermissions[$currentPage];
    if (!hasAnyPermission($requiredPerms, $permissions)) {
        setFlashMessage('You do not have permission to access this page.', 'error');
        header('Location: ' . APP_URL . '/admin/index.php');
        exit();
    }
}

/**
 * Check if user has admin access
 */
function hasAdminAccess() {
    $userType = getUserType();
    return in_array($userType, ['admin', 'super_admin']);
}

/**
 * Get admin role
 */
function getAdminRole($userId, $db) {
    $sql = "SELECT ar.role_name, ar.role_level 
            FROM admin_roles ar 
            JOIN users u ON u.admin_role_id = ar.id 
            WHERE u.id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$userId]);
    $role = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$role) {
        // Default role for admins without specific role
        return [
            'role_name' => 'Administrator',
            'role_level' => 1
        ];
    }
    
    return $role;
}

/**
 * Get admin permissions
 */
function getAdminPermissions($role, $db) {
    // Super admin has all permissions
    if (getUserType() === 'super_admin' || $role['role_level'] >= 10) {
        return [
            'view_dashboard' => true,
            'manage_users' => true,
            'approve_users' => true,
            'manage_locations' => true,
            'manage_products' => true,
            'manage_orders' => true,
            'view_orders' => true,
            'manage_prices' => true,
            'manage_content' => true,
            'manage_reports' => true,
            'manage_settings' => true,
            'view_logs' => true,
            'view_analytics' => true,
            'delete_users' => true,
            'ban_users' => true,
            'manage_roles' => true,
            'full_access' => true
        ];
    }
    
    // Get role-specific permissions
    $sql = "SELECT p.permission_key, p.permission_name 
            FROM admin_permissions p 
            JOIN role_permissions rp ON p.id = rp.permission_id 
            JOIN admin_roles ar ON rp.role_id = ar.id 
            WHERE ar.role_name = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$role['role_name']]);
    $perms = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $permissions = [];
    foreach ($perms as $perm) {
        $permissions[$perm['permission_key']] = true;
    }
    
    return $permissions;
}

/**
 * Check if user has any of the required permissions
 */
function hasAnyPermission($requiredPerms, $userPermissions) {
    foreach ($requiredPerms as $perm) {
        if (isset($userPermissions[$perm]) && $userPermissions[$perm]) {
            return true;
        }
    }
    return false;
}

/**
 * Check if user has specific admin permission
 */
function hasAdminPermission($permission) {
    global $permissions;
    return isset($permissions[$permission]) && $permissions[$permission];
}

/**
 * Render admin page header
 */
function renderAdminHeader($pageTitle, $breadcrumbs = []) {
    global $currentUserName, $adminRole, $db;
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="robots" content="noindex, nofollow">
        <title><?php echo $pageTitle; ?> - AIMS Admin</title>
        
        <!-- Favicon -->
        <link rel="icon" type="image/png" href="<?php echo APP_URL; ?>/assets/images/favicon.png">
        
        <!-- Bootstrap 5.3 CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
        
        <!-- Bootstrap Icons -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
        
        <!-- DataTables CSS -->
        <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
        
        <!-- Toastify CSS -->
        <link href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" rel="stylesheet">
        
        <!-- Admin Custom CSS -->
        <style>
            :root {
                --primary-color: #059669;
                --primary-dark: #047857;
                --primary-light: #10b981;
                --admin-sidebar-width: 260px;
            }
            
            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                background-color: #f8f9fa;
                overflow-x: hidden;
            }
            
            /* Admin Topbar */
            .admin-topbar {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                height: 60px;
                background: white;
                border-bottom: 1px solid #e5e7eb;
                z-index: 1040;
                padding: 0 20px;
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
            
            .admin-topbar .logo {
                font-size: 1.5rem;
                font-weight: bold;
                color: var(--primary-color);
                text-decoration: none;
            }
            
            .admin-topbar .logo i {
                font-size: 1.8rem;
            }
            
            /* Admin Sidebar */
            .admin-sidebar {
                position: fixed;
                top: 60px;
                left: 0;
                width: var(--admin-sidebar-width);
                height: calc(100vh - 60px);
                background: #1f2937;
                overflow-y: auto;
                z-index: 1030;
                transition: transform 0.3s ease;
            }
            
            .admin-sidebar::-webkit-scrollbar {
                width: 6px;
            }
            
            .admin-sidebar::-webkit-scrollbar-track {
                background: #374151;
            }
            
            .admin-sidebar::-webkit-scrollbar-thumb {
                background: #6b7280;
                border-radius: 3px;
            }
            
            .admin-sidebar .nav-section-title {
                color: #9ca3af;
                font-size: 0.75rem;
                font-weight: 600;
                text-transform: uppercase;
                padding: 20px 20px 10px;
                letter-spacing: 0.5px;
            }
            
            .admin-sidebar .nav-link {
                color: #d1d5db;
                padding: 12px 20px;
                display: flex;
                align-items: center;
                text-decoration: none;
                transition: all 0.2s ease;
                border-left: 3px solid transparent;
            }
            
            .admin-sidebar .nav-link:hover {
                background: #374151;
                color: white;
            }
            
            .admin-sidebar .nav-link.active {
                background: #059669;
                color: white;
                border-left-color: #10b981;
            }
            
            .admin-sidebar .nav-link i {
                margin-right: 12px;
                width: 20px;
                text-align: center;
                font-size: 1.1rem;
            }
            
            .admin-sidebar .badge {
                margin-left: auto;
                font-size: 0.7rem;
            }
            
            /* Admin Content */
            .admin-content {
                margin-left: var(--admin-sidebar-width);
                margin-top: 60px;
                padding: 30px;
                min-height: calc(100vh - 60px);
            }
            
            /* Breadcrumb */
            .admin-breadcrumb {
                background: transparent;
                padding: 0;
                margin-bottom: 20px;
            }
            
            .admin-breadcrumb .breadcrumb-item a {
                color: #6b7280;
                text-decoration: none;
            }
            
            .admin-breadcrumb .breadcrumb-item.active {
                color: #1f2937;
                font-weight: 500;
            }
            
            /* Cards */
            .stat-card {
                border-radius: 12px;
                border: none;
                transition: all 0.3s ease;
            }
            
            .stat-card:hover {
                transform: translateY(-5px);
                box-shadow: 0 10px 25px rgba(0,0,0,0.1);
            }
            
            /* Mobile Responsive */
            @media (max-width: 992px) {
                .admin-sidebar {
                    transform: translateX(-100%);
                }
                
                .admin-sidebar.show {
                    transform: translateX(0);
                    box-shadow: 5px 0 15px rgba(0,0,0,0.3);
                }
                
                .admin-content {
                    margin-left: 0;
                }
                
                .mobile-menu-toggle {
                    display: block !important;
                }
            }
            
            .mobile-menu-toggle {
                display: none;
                background: transparent;
                border: none;
                font-size: 1.5rem;
                color: #1f2937;
                cursor: pointer;
                padding: 5px 10px;
            }
            
            .mobile-menu-toggle:hover {
                background: #f3f4f6;
                border-radius: 5px;
            }
            
            /* Loading Overlay */
            .loading-overlay {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: none;
                align-items: center;
                justify-content: center;
                z-index: 9999;
            }
            
            .loading-overlay.show {
                display: flex;
            }
        </style>
    </head>
    <body>
        <!-- Admin Topbar -->
        <div class="admin-topbar">
            <div class="d-flex align-items-center">
                <button class="mobile-menu-toggle me-3" onclick="toggleSidebar()">
                    <i class="bi bi-list"></i>
                </button>
                <a href="<?php echo APP_URL; ?>/admin/" class="logo">
                    <i class="bi bi-shield-check"></i> AIMS Admin
                </a>
            </div>
            
            <div class="d-flex align-items-center gap-3">
                <!-- Quick Actions -->
                <a href="<?php echo APP_URL; ?>/dashboard/" class="btn btn-sm btn-outline-primary" title="View Site">
                    <i class="bi bi-eye"></i> <span class="d-none d-md-inline">View Site</span>
                </a>
                
                <!-- Notifications -->
                <div class="dropdown">
                    <button class="btn btn-sm position-relative" data-bs-toggle="dropdown">
                        <i class="bi bi-bell fs-5"></i>
                        <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" id="adminNotifBadge">
                            0
                        </span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end" style="width: 320px;">
                        <li><h6 class="dropdown-header">Admin Notifications</h6></li>
                        <li><hr class="dropdown-divider"></li>
                        <li id="adminNotifList">
                            <div class="text-center py-3 text-muted small">No notifications</div>
                        </li>
                    </ul>
                </div>
                
                <!-- User Menu -->
                <div class="dropdown">
                    <button class="btn btn-sm dropdown-toggle d-flex align-items-center" data-bs-toggle="dropdown">
                        <img src="<?php echo getAvatarUrl(); ?>" class="rounded-circle me-2" width="32" height="32">
                        <span class="d-none d-md-inline"><?php echo htmlspecialchars($currentUserName); ?></span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><div class="dropdown-header">
                            <strong><?php echo htmlspecialchars($currentUserName); ?></strong><br>
                            <small class="text-muted"><?php echo htmlspecialchars($adminRole['role_name']); ?></small>
                        </div></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="<?php echo APP_URL; ?>/profile/">
                            <i class="bi bi-person me-2"></i> My Profile
                        </a></li>
                        <li><a class="dropdown-item" href="<?php echo APP_URL; ?>/admin/settings.php">
                            <i class="bi bi-gear me-2"></i> Settings
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item text-danger" href="#" onclick="logout(); return false;">
                            <i class="bi bi-box-arrow-right me-2"></i> Logout
                        </a></li>
                    </ul>
                </div>
            </div>
        </div>
        
        <?php
        // Include sidebar
        require_once __DIR__ . '/admin-sidebar.php';
        ?>
        
        <!-- Admin Content -->
        <div class="admin-content">
            <?php if (!empty($breadcrumbs)): ?>
            <nav aria-label="breadcrumb" class="admin-breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="<?php echo APP_URL; ?>/admin/"><i class="bi bi-house-door"></i></a></li>
                    <?php foreach ($breadcrumbs as $index => $crumb): ?>
                        <?php if ($index === count($breadcrumbs) - 1): ?>
                            <li class="breadcrumb-item active" aria-current="page"><?php echo $crumb['title']; ?></li>
                        <?php else: ?>
                            <li class="breadcrumb-item"><a href="<?php echo $crumb['url']; ?>"><?php echo $crumb['title']; ?></a></li>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </ol>
            </nav>
            <?php endif; ?>
    <?php
}

/**
 * Render admin page footer
 */
function renderAdminFooter() {
    ?>
        </div> <!-- End admin-content -->
        
        <!-- Loading Overlay -->
        <div class="loading-overlay" id="loadingOverlay">
            <div class="spinner-border text-light" style="width: 3rem; height: 3rem;"></div>
        </div>
        
        <!-- jQuery -->
        <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
        
        <!-- Bootstrap Bundle -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
        
        <!-- DataTables -->
        <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
        
        <!-- SweetAlert2 -->
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        
        <!-- Toastify -->
        <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
        
        <!-- Chart.js -->
        <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
        
        <!-- Admin Common Scripts -->
        <script>
            const APP_URL = '<?php echo APP_URL; ?>';
            
            // Toggle sidebar on mobile
            function toggleSidebar() {
                const sidebar = document.querySelector('.admin-sidebar');
                if (sidebar) {
                    sidebar.classList.toggle('show');
                }
            }
            
            // Close sidebar when clicking outside on mobile
            document.addEventListener('click', function(event) {
                const sidebar = document.querySelector('.admin-sidebar');
                const toggle = document.querySelector('.mobile-menu-toggle');
                
                if (window.innerWidth <= 992 && sidebar) {
                    if (!sidebar.contains(event.target) && (!toggle || !toggle.contains(event.target))) {
                        sidebar.classList.remove('show');
                    }
                }
            });
            
            // Prevent sidebar close when clicking inside it
            const sidebar = document.querySelector('.admin-sidebar');
            if (sidebar) {
                sidebar.addEventListener('click', function(e) {
                    e.stopPropagation();
                });
            }
            
            // Show/Hide loading
            function showLoading() {
                const overlay = document.getElementById('loadingOverlay');
                if (overlay) {
                    overlay.classList.add('show');
                }
            }
            
            function hideLoading() {
                const overlay = document.getElementById('loadingOverlay');
                if (overlay) {
                    overlay.classList.remove('show');
                }
            }
            
            // Toast notifications
            function showToast(message, type) {
                type = type || 'info';
                const colors = {
                    success: 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)',
                    error: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)',
                    warning: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
                    info: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)'
                };
                
                if (typeof Toastify !== 'undefined') {
                    Toastify({
                        text: message,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        style: { background: colors[type] || colors.info, borderRadius: "10px", padding: "15px 20px" },
                        stopOnFocus: true
                    }).showToast();
                } else {
                    // Fallback to alert if Toastify not loaded
                    alert(message);
                }
            }
            
            // Logout function
            function logout() {
                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        title: 'Logout',
                        text: 'Are you sure you want to logout?',
                        icon: 'question',
                        showCancelButton: true,
                        confirmButtonColor: '#059669',
                        cancelButtonColor: '#6b7280',
                        confirmButtonText: 'Yes, logout'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            performLogout();
                        }
                    });
                } else {
                    if (confirm('Are you sure you want to logout?')) {
                        performLogout();
                    }
                }
            }
            
            function performLogout() {
                showLoading();
                if (typeof jQuery !== 'undefined') {
                    jQuery.post(APP_URL + '/api/auth.php', { action: 'logout' }, function(response) {
                        if (response.success) {
                            window.location.href = APP_URL + '/auth/login.php';
                        } else {
                            hideLoading();
                            showToast('Logout failed', 'error');
                        }
                    }).fail(function() {
                        hideLoading();
                        showToast('Connection error', 'error');
                    });
                } else {
                    // Fallback if jQuery not loaded
                    window.location.href = APP_URL + '/auth/logout.php';
                }
            }
            
            // Check for flash messages
            document.addEventListener('DOMContentLoaded', function() {
                <?php $flash = getFlashMessage(); if ($flash): ?>
                showToast('<?php echo addslashes($flash['message']); ?>', '<?php echo $flash['type']; ?>');
                <?php endif; ?>
            });
        </script>
    </body>
    </html>
    <?php
}
?>