<?php 
$title = __('nav.dashboard', 'Dashboard');
ob_start(); 
?>




<div class="row">
    <div class="col-md-3">
         <div class="col" id="dashboardStats">
              
              
                
                
            </div>
    </div>
</div>

<div class="row mt-4">
    <div class="col-12">
        <?php if ($_SESSION['user_role'] === 'adminx'): ?>
            <hr class="my-2">
            <div class="d-flex flex-wrap gap-2 mb-3">
                <a href="/samanta_crm/products" class="btn btn-outline-success">
                    <i class="fas fa-boxes"></i> <?= __('dashboard.products', 'Products') ?>
                </a>
                <a href="/samanta_crm/products/import" class="btn btn-outline-success">
                    <i class="fas fa-file-import"></i> <?= __('dashboard.import_products', 'Import Products') ?>
                </a>
                <a href="/samanta_crm/categories" class="btn btn-outline-success">
                    <i class="fas fa-layer-group"></i> <?= __('dashboard.categories', 'Categories') ?>
                </a>
                <a href="/samanta_crm/ingredients" class="btn btn-outline-success">
                    <i class="fas fa-carrot"></i> <?= __('dashboard.ingredients', 'Ingredients') ?>
                </a>
                <a href="/samanta_crm/units" class="btn btn-outline-success">
                    <i class="fas fa-ruler-combined"></i> <?= __('dashboard.units', 'Units') ?>
                </a>
                <a href="/samanta_crm/production-sites" class="btn btn-outline-success">
                    <i class="fas fa-industry"></i> <?= __('dashboard.production_sites', 'Production Sites') ?>
                </a>
                <a href="/samanta_crm/report-flags" class="btn btn-outline-success">
                    <i class="fas fa-flag"></i> <?= __('dashboard.report_flags', 'Report Flags') ?>
                </a>
            </div>
        <?php endif; ?>
    </div>
    
    <div class="col-md-12">
        <div class="row">
             <!-- stat cards -->
                <div class="col mb-3">
                    <div class="card text-white bg-warning bg-opacity-25 text-warning-emphasis shadow-none">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div class="d-flex align-items-center gap-2">
                                    <h4 class="mb-0"><?= $pendingOrders ?></h4>
                                    <p class="mb-0"><?= __('dashboard.pending_orders', 'Pending Orders') ?></p>
                                </div>
                                <div class="align-self-center text-warning-emphasis">
                                    <i class="fas fa-clock fa"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col mb-3">
                    <div class="card text-white bg-success bg-opacity-25 text-success-emphasis shadow-none">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div class="d-flex align-items-center gap-2">
                                    <h4 class="mb-0"><?= $totalOrders ?></h4>
                                    <p class="mb-0"><?= __('dashboard.total_orders', 'Total Orders') ?></p>
                                </div>
                                <div class="align-self-center">
                                    <i class="fas fa-shopping-cart fa"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
              
            <!-- stat cards end -->
        </div>
        <div class="card bg-transparent" id="latestOrders"> <div class="btn-group btn-group-sm mb-0" role="group" id="orderTypeFilter">
                        <button type="button" class="btn btn-outline-primary active p-3 rounded-top-4" data-type="all">
                            <?= __('common.all', 'All') ?> <span class="badge bg-primary position-absolute end-0 rounded-pill" id="countAll">0</span>
                        </button>
                        <button type="button" class="btn btn-outline-primary rounded-top-4 bg-secondary" data-type="daily">
                            <?= __('orders.type_daily', 'Daily') ?> <span class="badge bg-primary position-absolute end-0 rounded-pill" id="countDaily">0</span>
                        </button>
                        <button type="button" class="btn btn-outline-primary rounded-top-4 bg-secondary" data-type="additional">
                            <?= __('orders.type_additional', 'Additional') ?> <span class="badge bg-primary position-absolute end-0 rounded-pill" id="countAdditional">0</span>
                        </button>
                    </div>
            <div class="card-header d-flex justify-content-between align-items-center bg-light">
                <div class="d-flex align-items-center gap-2">
                    <h6 class="card-title mb-0 me-3">
                        <i class="fas fa-receipt"></i> <?= __('dashboard.latest_orders', 'Latest Orders') ?>
                    </h6>
                   
                </div>
                <div class="d-flex align-items-center gap-2 bg-">
                    <label class="mb-0 me-2 small"><?= __('common.show', 'Show') ?>:</label>
                    <select id="ordersPageSize" class="form-select form-select-sm" style="width: auto;">
                        <option value="5">5</option>
                        <option value="10">10</option>
                        <option value="20">20</option>
                    </select>
                </div>
            </div>
            <div class="card-body bg-white pt-0">
                <div class="table-responsive">
                    <table class="table table-hover table-sm mb-0" id="ordersTableDashboard">
                        <thead class="table-light">
                            <tr>
                                <th>#</th>
                                <th><?= __('common.customer', 'Customer') ?></th>
                                <th class="d-none d-lg-table-cell"><?= __('orders.order_date', 'Order Date') ?></th>
                                <th class="d-none d-md-table-cell"><?= __('common.type', 'Type') ?></th>
                                <th class="d-none d-lg-table-cell"><?= __('common.status', 'Status') ?></th>
                                <th class="d-none d-lg-table-cell"><?= __('orders.items', 'Items') ?></th>
                                <th class="text-end"><?= __('common.actions', 'Actions') ?></th>
                            </tr>
                        </thead>
                        <tbody id="ordersTableBody">
                            <tr>
                                <td colspan="7" class="text-center text-muted">
                                    <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                                    <?= __('common.loading', 'Loading') ?>...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="text-center mt-3">
                    <a href="/samanta_crm/orders" class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-list"></i> <?= __('dashboard.view_all_orders', 'View All Orders') ?>
                    </a>
                </div>
            </div>
        </div>
          <div class="col mt-3 mb-3" id="ingredientStockCard">
                    <div class="bg-transparent card" style="min-height: 100%;">
                        <div class="card-header d-flex justify-content-between align-items-center px-2 p-0">
                            <h6 class="mb-0 small">
                                <i class="fas fa-exclamation-triangle me-1"></i> 
                                <?= __('dashboard.stock_alerts', 'Stock Alerts') ?>
                            </h6>
                            <?php if (!empty($lowStockIngredients)): ?>
                                <span class="badge bg-danger rounded-pill"><?= count($lowStockIngredients) ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="card-body p-0">
                            <?php if (empty($lowStockIngredients)): ?>
                                <div class="p-3 text-center text-muted">
                                    <i class="fas fa-check-circle fa-2x mb-2 text-success"></i>
                                    <p class="mb-0 small"><?= __('dashboard.all_stock_ok', 'All ingredients in stock') ?></p>
                                </div>
                            <?php else: ?>
                                <div class="list-group list-group-flush">
                                    <?php foreach (array_slice($lowStockIngredients, 0, 5) as $ing): 
                                        $badgeClass = '';
                                        $icon = '';
                                        $statusText = '';
                                        switch($ing['stock_status']) {
                                            case 'critical_low':
                                                $badgeClass = 'bg-danger';
                                                $icon = 'fa-exclamation-circle';
                                                $statusText = __('dashboard.critical_low', 'Critical Low');
                                                break;
                                            case 'low':
                                                $badgeClass = 'warning text-warning';
                                                $icon = 'fa-exclamation-triangle';
                                                $statusText = __('dashboard.low', 'Low');
                                                break;
                                            case 'critical_high':
                                                $badgeClass = 'bg-danger';
                                                $icon = 'fa-arrow-up';
                                                $statusText = __('dashboard.critical_high', 'Critical High');
                                                break;
                                            case 'high':
                                                $badgeClass = 'bg-info';
                                                $icon = 'fa-arrow-up';
                                                $statusText = __('dashboard.high', 'High');
                                                break;
                                        }
                                    ?>
                                        <a href="/samanta_crm/ingredients/<?= $ing['id'] ?>/edit" class="list-group-item list-group-item-action py-2 px-3">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div class="flex-grow-1 me-2 d-flex">
                                                    <div class="small fw-bold text-truncate me-2"><?= htmlspecialchars($ing['name']) ?></div>
                                                    <div class="small ">
                                                        <code class="bg-opacity-25 bg-warning p-1 rounded-pill text-white"><?= formatUnit($ing['total_stock'], $ing['unit']) ?></code>
                                                    </div>
                                                </div>
                                                <span class="badge <?= $badgeClass ?> small pulse">
                                                    <i class="fas <?= $icon ?> me-1"></i><?= $statusText ?>
                                                </span>
                                            </div>
                                        </a>
                                    <?php endforeach; ?>
                                    <?php if (count($lowStockIngredients) > 5): ?>
                                        <a href="/samanta_crm/stock/ingredients" class="list-group-item list-group-item-action text-center py-2 small">
                                            <i class="fas fa-ellipsis-h me-1"></i>
                                            <?= __('dashboard.view_more_alerts', 'View all alerts') ?> 
                                            (<?= count($lowStockIngredients) - 5 ?> <?= __('common.more', 'more') ?>)
                                        </a>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
    </div>
</div></div>
<script>
// Latest Orders AJAX Loading
(function() {
    const STORAGE_KEY = 'dashboard_orders_pagesize';
    const STORAGE_TYPE_KEY = 'dashboard_orders_type';
    const pageSizeSelect = document.getElementById('ordersPageSize');
    const tableBody = document.getElementById('ordersTableBody');
    const typeButtons = document.querySelectorAll('#orderTypeFilter button');
    
    // Load saved preferences
    const savedPageSize = localStorage.getItem(STORAGE_KEY) || '5';
    const savedType = localStorage.getItem(STORAGE_TYPE_KEY) || 'all';
    pageSizeSelect.value = savedPageSize;
    
    // Set active type button
    typeButtons.forEach(btn => {
        if (btn.dataset.type === savedType) {
            btn.classList.add('active');
        } else {
            btn.classList.remove('active');
        }
    });
    
    function loadOrders() {
        const limit = pageSizeSelect.value;
        const activeType = document.querySelector('#orderTypeFilter button.active').dataset.type;
        
        // Show loading
        tableBody.innerHTML = `
            <tr>
                <td colspan="7" class="text-center text-muted">
                    <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                    <?= __('common.loading', 'Loading') ?>...
                </td>
            </tr>
        `;
        
        fetch(`/samanta_crm/orders/latest?limit=50`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.text();
            })
            .then(text => {
                let data;
                try {
                    data = JSON.parse(text);
                } catch (e) {
                    console.error('Invalid JSON response:', text);
                    throw new Error('Invalid JSON response from server');
                }
                
                if (data.success && data.orders) {
                    // Count by type
                    const counts = {
                        all: data.orders.length,
                        daily: data.orders.filter(o => o.order_type === 'daily').length,
                        additional: data.orders.filter(o => o.order_type === 'additional').length
                    };
                    
                    // Update badges
                    document.getElementById('countAll').textContent = counts.all;
                    document.getElementById('countDaily').textContent = counts.daily;
                    document.getElementById('countAdditional').textContent = counts.additional;
                    
                    // Filter orders by active type
                    let filteredOrders = data.orders;
                    if (activeType !== 'all') {
                        filteredOrders = data.orders.filter(o => o.order_type === activeType);
                    }
                    
                    // Limit to page size
                    filteredOrders = filteredOrders.slice(0, parseInt(limit));
                    
                    if (filteredOrders.length === 0) {
                        tableBody.innerHTML = `
                            <tr>
                                <td colspan="7" class="text-center text-muted">
                                    <?= __('orders.no_orders_found', 'No orders found') ?>
                                </td>
                            </tr>
                        `;
                        return;
                    }
                    
                    tableBody.innerHTML = filteredOrders.map(order => {
                        const orderDate = new Date(order.order_date);
                        const formattedDate = orderDate.toLocaleDateString('pl-PL', { 
                            year: 'numeric', 
                            month: 'short', 
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit'
                        });
                        
                        const shortDate = orderDate.toLocaleDateString('pl-PL', { 
                            day: '2-digit',
                            month: '2-digit',
                            year: '2-digit'
                        });
                        
                        const timeOnly = orderDate.toLocaleTimeString('pl-PL', { 
                            hour: '2-digit',
                            minute: '2-digit'
                        });
                        
                        const statusBadge = {
                            'pending': '<span class="badge bg-warning text-dark">Pending</span>',
                            'processing': '<span class="badge bg-info">Processing</span>',
                            'completed': '<span class="badge bg-success-subtle text-success-emphasis">Completed</span>',
                            'cancelled': '<span class="badge bg-danger">Cancelled</span>'
                        }[order.status] || `<span class="badge bg-secondary">${order.status}</span>`;
                        
                        const typeBadge = {
                            'daily': '<span class="badge bg-primary-subtle text-primary-emphasis">Daily</span>',
                            'additional': '<span class="badge bg-secondary-subtle text-secondary-emphasis">Additional</span>'
                        }[order.order_type] || `<span class="badge bg-light text-dark">${order.order_type}</span>`;
                        
                        return `
                            <tr>
                                <td><code class="small">#${order.id}</code></td>
                                <td class="d-flex flex-row flex-wrap align-items-center gap-1 justify-content-between">
                                    <strong class="small">${escapeHtml(order.customer_name)}</strong>
                                    <!-- Mobile wrapped info -->
                                    <div class="d-md-none small text-muted mt-1">
                                        ${typeBadge}
                                        ${statusBadge}
                                    </div>
                                    <!-- Tablet wrapped info -->
                                    <div class="d-lg-none small text-muted mt-1">
                                        <i class="fas fa-calendar me-1"></i>${shortDate} ${timeOnly}
                                    </div>
                                </td>
                                <td class="d-none d-lg-table-cell text-nowrap small">
                                    ${shortDate}
                                    <br>
                                    <span class="text-muted" style="font-size:0.7rem">${timeOnly}</span>
                                </td>
                                <td class="d-none d-md-table-cell">${typeBadge}</td>
                                <td class="d-none d-md-table-cell">${statusBadge}</td>
                                <td class="d-none d-lg-table-cell"><span class="bg-light text-dark fw-bold"><code>${order.items_count}</code></span></td>
                                <td class="text-end">
                                    <a href="/samanta_crm/orders/${order.id}" class="btn btn-sm btn-outline-primary" title="<?= __('common.view', 'View') ?>">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                </td>
                            </tr>
                        `;
                    }).join('');
                } else {
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="7" class="text-center text-danger">
                                <?= __('common.error', 'Error loading data') ?>
                            </td>
                        </tr>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading orders:', error);
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="7" class="text-center text-danger">
                            <?= __('common.error', 'Error loading data') ?>
                        </td>
                    </tr>
                `;
            });
    }
    
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    // Load orders on page load
    loadOrders();
    
    // Update when page size changes
    pageSizeSelect.addEventListener('change', function() {
        localStorage.setItem(STORAGE_KEY, this.value);
        loadOrders();
    });
    
    // Handle type filter buttons
    typeButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            typeButtons.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            localStorage.setItem(STORAGE_TYPE_KEY, this.dataset.type);
            loadOrders();
        });
    });
})();
</script>

<?php 
$content = ob_get_clean();
include '../app/Views/layout.php'; 
?>
