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

// Buyer system should already be loaded by index.php
// If not, we need to initialize it
if (!isset($buyerSystem)) {
    require_once __DIR__ . '/../../config/config.php';
    require_once __DIR__ . '/../BuyerSystem.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();
    
    // Only buyers can access
    if ($currentUserType !== 'buyer') {
        header('Location: ' . APP_URL . '/dashboard/');
        exit();
    }
    
    // Initialize database and buyer system
    $database = \App\Database::getInstance();
    $db = $database->getConnection();
    $buyerSystem = new BuyerSystem($database, $currentUserId);
} else {
    // Use existing variables - 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 buyer details
$buyerProfile = $buyerSystem->getProfile();
$buyerType = $buyerSystem->getBuyerType();
$isVerified = $buyerSystem->isVerified();
$hasCompleteProfile = $buyerSystem->hasCompleteProfile();

// Define page permissions
$pagePermissions = [
    'index.php' => [],
    'dashboard.php' => [],
    'orders.php' => [],
    'suppliers.php' => ['manage_suppliers'],
    'purchase-requests.php' => ['request_quotes'],
    'contracts.php' => ['contract_farming'],
    'analytics.php' => ['view_analytics'],
    'bulk-orders.php' => ['bulk_purchase'],
    'quality-specs.php' => ['quality_specifications'],
];

// Check page-specific permissions
$currentPage = basename($_SERVER['PHP_SELF']);
if (isset($pagePermissions[$currentPage]) && !empty($pagePermissions[$currentPage])) {
    $hasAccess = false;
    foreach ($pagePermissions[$currentPage] as $perm) {
        if ($buyerSystem->hasPermission($perm)) {
            $hasAccess = true;
            break;
        }
    }
    
    if (!$hasAccess) {
        setFlashMessage('You do not have permission to access this page. Consider upgrading your buyer profile.', 'warning');
        header('Location: ' . APP_URL . '/buyer/dashboard.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;
        }
        
        $name = isset($_SESSION['full_name']) ? urlencode($_SESSION['full_name']) : 'Buyer';
        return "https://ui-avatars.com/api/?name={$name}&background=3b82f6&color=fff&size=128";
    }
}

/**
 * Helper function for flash messages
 */
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 buyer page header
 */
function renderBuyerHeader($pageTitle, $breadcrumbs = []) {
    global $currentUserName, $buyerType, $buyerProfile, $buyerSystem, $db, $currentUserId, $currentUserType, $isVerified, $hasCompleteProfile;
    
    $typeColors = [
        'individual' => '#6b7280',
        'retailer' => '#3b82f6',
        'wholesaler' => '#10b981',
        'processor' => '#f59e0b',
        'exporter' => '#ef4444'
    ];
    
    $typeColor = $typeColors[$buyerType] ?? '#3b82f6';
    $businessName = $buyerProfile['business_name'] ?? 'Buyer Account';
    ?>
    <!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 Buyer Portal</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">
        
        <!-- Select2 CSS -->
        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
        
        <!-- Buyer Custom CSS -->
        <style>
            :root {
                --primary-color: #3b82f6;
                --primary-dark: #2563eb;
                --primary-light: #60a5fa;
                --buyer-type-color: <?php echo $typeColor; ?>;
                --buyer-sidebar-width: 260px;
            }
            
            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                background-color: #f8f9fa;
                overflow-x: hidden;
            }
            
            /* Buyer Topbar */
            .buyer-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(--buyer-type-color);
                z-index: 1040;
                padding: 0 20px;
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
            
            .buyer-topbar .logo {
                font-size: 1.5rem;
                font-weight: bold;
                color: white;
                text-decoration: none;
            }
            
            .buyer-topbar .logo i {
                font-size: 1.8rem;
            }
            
            .type-badge {
                background-color: var(--buyer-type-color);
                color: white;
                padding: 4px 12px;
                border-radius: 20px;
                font-size: 0.75rem;
                font-weight: 600;
                text-transform: uppercase;
            }
            
            /* Buyer Sidebar */
            .buyer-sidebar {
                position: fixed;
                top: 60px;
                left: 0;
                width: var(--buyer-sidebar-width);
                height: calc(100vh - 60px);
                background: #1f2937;
                overflow-y: auto;
                z-index: 1030;
                transition: transform 0.3s ease;
            }
            
            .buyer-sidebar::-webkit-scrollbar {
                width: 6px;
            }
            
            .buyer-sidebar::-webkit-scrollbar-track {
                background: #374151;
            }
            
            .buyer-sidebar::-webkit-scrollbar-thumb {
                background: #6b7280;
                border-radius: 3px;
            }
            
            .buyer-sidebar .nav-section-title {
                color: #9ca3af;
                font-size: 0.75rem;
                font-weight: 600;
                text-transform: uppercase;
                padding: 20px 20px 10px;
                letter-spacing: 0.5px;
            }
            
            .buyer-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;
            }
            
            .buyer-sidebar .nav-link:hover {
                background: #374151;
                color: white;
            }
            
            .buyer-sidebar .nav-link.active {
                background: var(--primary-color);
                color: white;
                border-left-color: var(--buyer-type-color);
            }
            
            .buyer-sidebar .nav-link i {
                margin-right: 12px;
                width: 20px;
                text-align: center;
                font-size: 1.1rem;
            }
            
            .buyer-sidebar .badge {
                margin-left: auto;
                font-size: 0.7rem;
            }
            
            /* Buyer Content */
            .buyer-content {
                margin-left: var(--buyer-sidebar-width);
                margin-top: 60px;
                padding: 30px;
                min-height: calc(100vh - 60px);
            }
            
            /* Breadcrumb */
            .buyer-breadcrumb {
                background: transparent;
                padding: 0;
                margin-bottom: 20px;
            }
            
            .buyer-breadcrumb .breadcrumb-item a {
                color: #6b7280;
                text-decoration: none;
            }
            
            .buyer-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);
            }
            
            /* Verification Badge */
            .verification-status {
                display: inline-flex;
                align-items: center;
                gap: 5px;
                padding: 4px 10px;
                border-radius: 15px;
                font-size: 0.75rem;
                font-weight: 600;
            }
            
            .verification-status.verified {
                background-color: #d1fae5;
                color: #065f46;
            }
            
            .verification-status.pending {
                background-color: #fef3c7;
                color: #92400e;
            }
            
            .verification-status.not-verified {
                background-color: #fee2e2;
                color: #991b1b;
            }
            
            /* Mobile Responsive */
            @media (max-width: 992px) {
                .buyer-sidebar {
                    transform: translateX(-100%);
                }
                
                .buyer-sidebar.show {
                    transform: translateX(0);
                    box-shadow: 5px 0 15px rgba(0,0,0,0.3);
                }
                
                .buyer-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>
        <!-- Buyer Topbar -->
        <div class="buyer-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; ?>/buyer/" class="logo">
                    <i class="bi bi-cart-check"></i> AIMS Buyer
                </a>
                <span class="type-badge ms-3"><?php echo strtoupper($buyerType); ?></span>
            </div>
            
            <div class="d-flex align-items-center gap-3">
                <!-- Verification Status -->
                <?php if ($buyerSystem->isVerified()): ?>
                <span class="verification-status verified">
                    <i class="bi bi-patch-check-fill"></i> Verified
                </span>
                <?php else: ?>
                <span class="verification-status not-verified">
                    <i class="bi bi-exclamation-circle-fill"></i> Not Verified
                </span>
                <?php endif; ?>
                
                <!-- Quick Actions -->
                <a href="<?php echo APP_URL; ?>/dashboard/" class="btn btn-sm btn-light" title="Main Site">
                    <i class="bi bi-house"></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="buyerNotifBadge">
                            0
                        </span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end" style="width: 320px;">
                        <li><h6 class="dropdown-header">Notifications</h6></li>
                        <li><hr class="dropdown-divider"></li>
                        <li id="buyerNotifList">
                            <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($businessName); ?></small><br>
                            <small class="text-muted"><?php echo $buyerSystem->getBuyerTypeBadge(); ?></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; ?>/buyer/settings.php">
                            <i class="bi bi-gear me-2"></i> Buyer 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__ . '/sidebar.php';
        ?>
        
        <!-- Buyer Content -->
        <div class="buyer-content">
            <?php if (!empty($breadcrumbs)): ?>
            <nav aria-label="breadcrumb" class="buyer-breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="<?php echo APP_URL; ?>/buyer/"><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 buyer page footer
 */
function renderBuyerFooter() {
    ?>
        </div> <!-- End buyer-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>
        
        <!-- Select2 -->
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
        
        <!-- Buyer Common Scripts -->
        <script>
            const APP_URL = '<?php echo APP_URL; ?>';
            
            // Toggle sidebar on mobile
            function toggleSidebar() {
                const sidebar = document.querySelector('.buyer-sidebar');
                if (sidebar) {
                    sidebar.classList.toggle('show');
                }
            }
            
            // Close sidebar when clicking outside on mobile
            document.addEventListener('click', function(event) {
                const sidebar = document.querySelector('.buyer-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('.buyer-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: '#3b82f6',
                        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';
                }
            }
            
            // Initialize Select2
            $(document).ready(function() {
                if (typeof $.fn.select2 !== 'undefined') {
                    $('.select2').select2({
                        theme: 'bootstrap-5'
                    });
                }
            });
            
            // 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
}