<?php
/**
 * ============================================================================
 * extension/includes/base.php - Extension Base Layout & Access Control
 * Handles extension officer authentication, permissions, and common layout
 * ============================================================================
 */

// Extension system should already be loaded by index.php
// If not, we need to initialize it
if (!isset($extensionSystem)) {
    require_once __DIR__ . '/../../config/config.php';
    require_once __DIR__ . '/ExtensionSystem.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();
    
    // Initialize database and extension system
    $database = \App\Database::getInstance();
    $db = $database->getConnection();
    $extensionSystem = new ExtensionSystem($database, $currentUserId);
} else {
    // Use existing variables from index.php - ensure they're set
    if (!isset($currentUserId)) {
        $currentUserId = getUserId();
    }
    if (!isset($currentUserType)) {
        $currentUserType = getUserType();
    }
    if (!isset($currentUserName)) {
        $currentUserName = getUserName();
    }
    if (!isset($db)) {
        $database = \App\Database::getInstance();
        $db = $database->getConnection();
    }
}

// Include helper functions
require_once __DIR__ . '/helpers.php';

// Alias for compatibility
$userName = $currentUserName;

// Get user assignment details
$userLevel = $extensionSystem->getUserLevel();
$userRole = $extensionSystem->getUserRole();
$coverageArea = $extensionSystem->getCoverageName();
$hasAssignment = $extensionSystem->hasAssignment();
$isAdmin = in_array($currentUserType, ['admin', 'super_admin']);

// Define page permissions
$pagePermissions = [
    'index.php' => [],
    'dashboard.php' => [],
    'subordinates.php' => ['manage_region', 'manage_district', 'manage_subcounty', 'manage_parish'],
    'farmers.php' => [],
    'services.php' => [],
    'schedule-service.php' => ['conduct_visits', 'conduct_training'],
    'reports.php' => ['submit_reports'],
    'resources.php' => ['create_resources'],
    'analytics.php' => ['view_reports', 'view_all_reports'],
    'assignments.php' => ['assign_regional', 'assign_district', 'assign_subcounty', 'assign_parish']
];

// Check page-specific permissions (only if user has assignment or is admin)
$currentPage = basename($_SERVER['PHP_SELF']);
if (($hasAssignment || $isAdmin) && isset($pagePermissions[$currentPage]) && !empty($pagePermissions[$currentPage])) {
    $hasAccess = false;
    foreach ($pagePermissions[$currentPage] as $perm) {
        if ($extensionSystem->hasPermission($perm)) {
            $hasAccess = true;
            break;
        }
    }
    
    if (!$hasAccess && !$isAdmin) {
        setFlashMessage('You do not have permission to access this page.', 'error');
        header('Location: ' . APP_URL . '/extension/index.php');
        exit();
    }
}

/**
 * Helper function to get avatar URL
 */
if (!function_exists('getAvatarUrl')) {
    function getAvatarUrl($profilePicture = null) {
        if ($profilePicture === null && isset($_SESSION['profile_picture'])) {
            $profilePicture = $_SESSION['profile_picture'];
        }
        
        if (!empty($profilePicture) && file_exists(UPLOAD_PATH . 'profiles/' . $profilePicture)) {
            return APP_URL . '/uploads/profiles/' . $profilePicture;
        }
        
        // Return default avatar - using UI Avatars service
        $name = isset($_SESSION['full_name']) ? urlencode($_SESSION['full_name']) : 'User';
        return "https://ui-avatars.com/api/?name={$name}&background=059669&color=fff&size=128";
    }
}

/**
 * Helper function for flash messages (if not already defined)
 */
if (!function_exists('setFlashMessage')) {
    function setFlashMessage($message, $type = 'info') {
        $_SESSION['flash_message'] = $message;
        $_SESSION['flash_type'] = $type;
    }
}

if (!function_exists('getFlashMessage')) {
    function getFlashMessage() {
        if (isset($_SESSION['flash_message'])) {
            $message = [
                'message' => $_SESSION['flash_message'],
                'type' => $_SESSION['flash_type'] ?? 'info'
            ];
            unset($_SESSION['flash_message']);
            unset($_SESSION['flash_type']);
            return $message;
        }
        return null;
    }
}

/**
 * Render extension page header
 */
function renderExtensionHeader($pageTitle, $breadcrumbs = []) {
    global $currentUserName, $userRole, $userLevel, $coverageArea, $db, $currentUserId, $currentUserType, $extensionSystem, $hasAssignment, $isAdmin;
    
    $levelColors = [
        'national' => '#6366f1',
        'regional' => '#ef4444',
        'district' => '#f59e0b',
        'subcounty' => '#10b981',
        'parish' => '#06b6d4',
        'village' => '#84cc16'
    ];
    
    $levelColor = $levelColors[$userLevel] ?? '#059669';
    ?>
    <!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 htmlspecialchars($pageTitle); ?> - AIMS Extension</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">
        
        <!-- Extension Custom CSS -->
        <style>
            :root {
                --primary-color: #059669;
                --primary-dark: #047857;
                --primary-light: #10b981;
                --level-color: <?php echo $levelColor; ?>;
                --extension-sidebar-width: 260px;
            }
            
            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                background-color: #f8f9fa;
                overflow-x: hidden;
            }
            
            /* Extension Topbar */
            .extension-topbar {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                height: 60px;
                background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
                border-bottom: 3px solid var(--level-color);
                z-index: 1040;
                padding: 0 20px;
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
            
            .extension-topbar .logo {
                font-size: 1.5rem;
                font-weight: bold;
                color: white;
                text-decoration: none;
            }
            
            .extension-topbar .logo i {
                font-size: 1.8rem;
            }
            
            .level-badge {
                background-color: var(--level-color);
                color: white;
                padding: 4px 12px;
                border-radius: 20px;
                font-size: 0.75rem;
                font-weight: 600;
                text-transform: uppercase;
            }
            
            /* Extension Sidebar */
            .extension-sidebar {
                position: fixed;
                top: 60px;
                left: 0;
                width: var(--extension-sidebar-width);
                height: calc(100vh - 60px);
                background: #1f2937;
                overflow-y: auto;
                z-index: 1030;
                transition: transform 0.3s ease;
            }
            
            .extension-sidebar::-webkit-scrollbar {
                width: 6px;
            }
            
            .extension-sidebar::-webkit-scrollbar-track {
                background: #374151;
            }
            
            .extension-sidebar::-webkit-scrollbar-thumb {
                background: #6b7280;
                border-radius: 3px;
            }
            
            .extension-sidebar .nav-section-title {
                color: #9ca3af;
                font-size: 0.75rem;
                font-weight: 600;
                text-transform: uppercase;
                padding: 20px 20px 10px;
                letter-spacing: 0.5px;
            }
            
            .extension-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;
            }
            
            .extension-sidebar .nav-link:hover {
                background: #374151;
                color: white;
            }
            
            .extension-sidebar .nav-link.active {
                background: var(--primary-color);
                color: white;
                border-left-color: var(--level-color);
            }
            
            .extension-sidebar .nav-link i {
                margin-right: 12px;
                width: 20px;
                text-align: center;
                font-size: 1.1rem;
            }
            
            .extension-sidebar .badge {
                margin-left: auto;
                font-size: 0.7rem;
            }
            
            /* Extension Content */
            .extension-content {
                margin-left: var(--extension-sidebar-width);
                margin-top: 60px;
                padding: 30px;
                min-height: calc(100vh - 60px);
            }
            
            /* Breadcrumb */
            .extension-breadcrumb {
                background: transparent;
                padding: 0;
                margin-bottom: 20px;
            }
            
            .extension-breadcrumb .breadcrumb-item a {
                color: #6b7280;
                text-decoration: none;
            }
            
            .extension-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) {
                .extension-sidebar {
                    transform: translateX(-100%);
                }
                
                .extension-sidebar.show {
                    transform: translateX(0);
                    box-shadow: 5px 0 15px rgba(0,0,0,0.3);
                }
                
                .extension-content {
                    margin-left: 0;
                }
                
                .mobile-menu-toggle {
                    display: block !important;
                }
            }
            
            .mobile-menu-toggle {
                display: none;
                background: transparent;
                border: none;
                font-size: 1.5rem;
                color: white;
                cursor: pointer;
                padding: 5px 10px;
            }
            
            .mobile-menu-toggle:hover {
                background: rgba(255,255,255,0.1);
                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>
        <!-- Extension Topbar -->
        <div class="extension-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; ?>/extension/" class="logo">
                    <i class="bi bi-person-badge"></i> AIMS Extension
                </a>
                <span class="level-badge ms-3"><?php echo strtoupper($userLevel ?? 'OFFICER'); ?></span>
            </div>
            
            <div class="d-flex align-items-center gap-3">
                <!-- Quick Actions -->
                <a href="<?php echo APP_URL; ?>/dashboard/" class="btn btn-sm btn-light" title="View Site">
                    <i class="bi bi-eye"></i> <span class="d-none d-md-inline">Main Site</span>
                </a>
                
                <!-- Notifications -->
                <div class="dropdown">
                    <button class="btn btn-sm btn-light 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="extensionNotifBadge">
                            0
                        </span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end" style="width: 320px;">
                        <li><h6 class="dropdown-header">Extension Notifications</h6></li>
                        <li><hr class="dropdown-divider"></li>
                        <li id="extensionNotifList">
                            <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 btn-light 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($userRole ?? 'Extension Officer'); ?></small><br>
                            <small class="text-muted"><i class="bi bi-geo-alt"></i> <?php echo htmlspecialchars($coverageArea); ?></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><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__ . '/sidebar.php';
        ?>
        
        <!-- Extension Content -->
        <div class="extension-content">
            <?php if (!empty($breadcrumbs)): ?>
            <nav aria-label="breadcrumb" class="extension-breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="<?php echo APP_URL; ?>/extension/"><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 htmlspecialchars($crumb['title']); ?></li>
                        <?php else: ?>
                            <li class="breadcrumb-item"><a href="<?php echo htmlspecialchars($crumb['url']); ?>"><?php echo htmlspecialchars($crumb['title']); ?></a></li>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </ol>
            </nav>
            <?php endif; ?>
    <?php
}

/**
 * Render extension page footer
 */
function renderExtensionFooter() {
    ?>
        </div> <!-- End extension-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>
        
        <!-- Extension Common Scripts -->
        <script>
            const APP_URL = '<?php echo APP_URL; ?>';
            
            // Toggle sidebar on mobile
            function toggleSidebar() {
                const sidebar = document.querySelector('.extension-sidebar');
                if (sidebar) {
                    sidebar.classList.toggle('show');
                }
            }
            
            // Close sidebar when clicking outside on mobile
            document.addEventListener('click', function(event) {
                const sidebar = document.querySelector('.extension-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('.extension-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 {
                    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 {
                    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
}