<?php

include '../../includes/header.php';


$auth = new Auth($conn);
$auth->enforceSuperAdminOrWarehousePrivileges($_SESSION['user_id']);


$database = new Database();
$conn = $database->getConnection();


require_once __DIR__ . '/../../classes/Inventory.php';
require_once __DIR__ . '/../../classes/Shipment.php';
require_once __DIR__ . '/../../classes/Sales.php';

$inventory = new Inventory($conn);
$shipment = new Shipment($conn);
$sales = new Sales($conn);


$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-t');


$warehouseStats = $inventory->getWarehouseStats();
$lowStockStats = $sales->getLowStockItems(7);
$warehouseShipments = $shipment->getWarehouseShipments($startDate, $endDate);
?>

<style>

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Roboto', sans-serif;
        font-size: 14px;
        line-height: 1.6;
        color: #333;
        background-color: #f8f9fa;
    }

    .container {
        width: 100%;
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 15px;
    }


    .dashboard-container {
        display: flex;
        width: 100%;
        margin-top: 20px;
    }


    .sidebar {
        width: 250px;
        background-color: #343a40;
        color: white;
        padding: 20px;
        position: fixed;
        top: 0;
        left: 0;
        height: 100vh;
        overflow-y: auto;
        z-index: 100;
    }

    .sidebar-heading {
        padding: 10px 0;
        font-size: 18px;
        font-weight: 500;
        border-bottom: 1px solid rgba(255,255,255,0.1);
        margin-bottom: 15px;
    }

    .sidebar-menu {
        list-style: none;
        padding: 0;
        margin: 0 0 25px 0;
    }

    .sidebar-menu li {
        margin-bottom: 5px;
    }

    .sidebar-menu a {
        display: block;
        padding: 10px 15px;
        color: rgba(255,255,255,0.8);
        text-decoration: none;
        transition: all 0.3s;
        border-radius: 4px;
    }

    .sidebar-menu a:hover {
        background-color: rgba(255,255,255,0.1);
        color: white;
    }

    .sidebar-menu i {
        margin-right: 10px;
        width: 20px;
        text-align: center;
    }

    .sidebar-section {
        margin-bottom: 25px;
    }


    .main-content {
        flex: 1;
        margin-left: 250px;
        padding: 20px;
        width: calc(100% - 250px);
    }


    .card {
        background-color: white;
        border-radius: 5px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        margin-bottom: 20px;
        width: 100%;
    }

    .card-header {
        padding: 15px 20px;
        border-bottom: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .card-header h2, .card-header h5 {
        margin: 0;
        font-size: 1.2rem;
    }

    .card-body {
        padding: 20px;
    }


    .chart-container {
        position: relative;
        height: 350px;
        margin-bottom: 20px;
    }


    .summary-card {
        border-radius: 5px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        transition: transform 0.3s;
        margin-bottom: 20px;
    }

    .summary-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 15px rgba(0,0,0,0.2);
    }


    .filter-form {
        background-color: #f8f9fa;
        padding: 15px;
        border-radius: 5px;
        margin-bottom: 20px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    }


    footer {
        margin-left: 250px;
        background-color: #f8f9fa;
        text-align: center;
        padding: 15px 0;
        border-top: 1px solid #eee;
        width: calc(100% - 250px);
    }


    @media (max-width: 768px) {
        .sidebar {
            width: 200px;
        }
        .main-content, footer {
            margin-left: 200px;
            width: calc(100% - 200px);
        }
    }
</style>

<div class="dashboard-container">
    <div class="sidebar">
        <div class="sidebar-heading">Warehouse Dashboard</div>

        <div class="sidebar-section">
            <div class="sidebar-heading">Warehouse Operations</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../inventory/add_items_dashboard2.php">
                        <i class="fas fa-shipping-fast"></i> Ship Items
                    </a>
                </li>
                <li>
                    <a href="../inventory/choose_warehouse_form.php">
                        <i class="fas fa-dolly-flatbed"></i> Add to Warehouse
                    </a>
                </li>
                <li>
                    <a href="../inventory/product_stock_code_generator.php">
                        <i class="fas fa-tags"></i> Product Stock Codes
                    </a>
                </li>
                <li>
                    <a href="../inventory/get_branch_inventory.php">
                        <i class="fas fa-warehouse"></i> Branch Stocks
                    </a>
                </li>
                <li>
                    <a href="../inventory/barcode_labels.php">
                        <i class="fas fa-barcode"></i> Barcode Labels
                    </a>
                </li>
                <li>
                    <a href="../shipments/shipment_dashboard.php">
                        <i class="fas fa-truck"></i> Shipment Records
                    </a>
                </li>
                <li>
                    <a href="../inventory/sold_items_dashboard.php">
                        <i class="fas fa-receipt"></i> Sold Items
                    </a>
                </li>
                <li>
                    <a href="../tracking/item_tracking.php">
                        <i class="fas fa-search"></i> Item Tracking
                    </a>
                </li>
                <li>
                    <a href="../discrepancies/index.php">
                        <i class="fas fa-exclamation-triangle"></i> Discrepancies
                    </a>
                </li>
                <li>
                    <a href="../disposals/index.php">
                        <i class="fas fa-archive"></i> Inventory Disposals
                    </a>
                </li>
                <li>
                    <a href="../reminders/index.php">
                        <i class="fas fa-bell"></i> Renewal Reminders
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-section">
            <div class="sidebar-heading">Sales & Transactions</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../sales/create_sale.php">
                        <i class="fas fa-cash-register"></i> Record Sales
                    </a>
                </li>
                <li>
                    <a href="../sales/list_quotations.php">
                        <i class="fas fa-file-invoice-dollar"></i> Quotations
                    </a>
                </li>
                <li>
                    <a href="../orders/list_orders.php">
                        <i class="fas fa-shopping-cart"></i> Orders
                    </a>
                </li>
                <li>
                    <a href="../customer_service/index.php">
                        <i class="fas fa-headset"></i> Customer Claims & Service
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-section">
            <div class="sidebar-heading">Inventory & Stock</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../stocktaking/stocktaking_dashboard.php">
                        <i class="fas fa-clipboard-check"></i> Stock Taking
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-section">
            <div class="sidebar-heading">Reports & Finance</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../sales/weekly2.php">
                        <i class="fas fa-chart-bar"></i> Sales Reports
                    </a>
                </li>
                <li>
                    <a href="../laybuy_&_loans/laybuy_and_loans.php">
                        <i class="fas fa-hand-holding-usd"></i> Lay-Buys
                    </a>
                </li>
                <li>
                    <a href="../reports/top_selling_items.php">
                        <i class="fas fa-trophy"></i> Top Selling Items
                    </a>
                </li>
                <li>
                    <a href="../reports/branch_reports.php">
                        <i class="fas fa-history"></i> Historical Reports
                    </a>
                </li>
                <li>
                    <a href="../logs/system_logs.php">
                        <i class="fas fa-clipboard-list"></i> System Logs
                    </a>
                </li>


            </ul>
        </div>
    </div>

    <div class="main-content">
        <div class="container">
            <h1 class="mb-4">Warehouse Dashboard</h1>
            <p class="text-muted">Monitor warehouse inventory, shipments, and operations</p>

            <div class="card filter-form mb-4">
                <div class="card-body">
                    <form method="GET" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" class="row g-3">
                        <div class="col-md-3">
                            <label for="start_date" class="form-label">Start Date</label>
                            <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $startDate; ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="end_date" class="form-label">End Date</label>
                            <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $endDate; ?>">
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary w-100">Apply Filter</button>
                        </div>
                    </form>
                </div>
            </div>



            <div class="row mb-4">
                <div class="col-md-12 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h5>Low Stock Alert</h5>
                            <small class="text-muted">Items below <?php echo $lowStockStats['low_stock_threshold']; ?> units</small>
                        </div>
                        <div class="card-body">
                            <?php if (empty($lowStockStats['low_stock_items'])): ?>
                                <div class="text-center text-success">
                                    <i class="fas fa-check-circle fa-3x mb-3"></i>
                                    <h5>All items are well stocked!</h5>
                                    <p class="text-muted">No items are below the low stock threshold.</p>
                                </div>
                            <?php else: ?>
                                <a href="../inventory/low_stock_items.php" class="text-decoration-none" style="cursor: pointer;">
                                    <div class="chart-container">
                                        <canvas id="lowStockChart"></canvas>
                                    </div>
                                    <div class="mt-3 text-center">
                                        <small class="text-muted">
                                            <strong><?php echo $lowStockStats['total_low_stock_items']; ?> items</strong> need restocking
                                            (Total value: MWK <?php echo number_format($lowStockStats['total_low_stock_value'], 2); ?>)
                                        </small>
                                        <br>
                                        <small class="text-primary">
                                            <i class="fas fa-external-link-alt"></i> Click to view full list
                                        </small>
                                    </div>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>


            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5>Recent Shipments</h5>
                        </div>
                        <div class="card-body">
                            <?php if (empty($warehouseShipments)): ?>
                                <p class="text-muted text-center">No shipments found for the selected period.</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>Shipment ID</th>
                                                <th>Destination</th>
                                                <th>Items</th>
                                                <th>Status</th>
                                                <th>Date</th>
                                                <th>Created By</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach (array_slice($warehouseShipments, 0, 10) as $shipment): ?>
                                                <tr>
                                                    <td><a href="../shipments/view_shipment.php?id=<?php echo $shipment['shipment_id']; ?>" class="text-decoration-none text-primary">#<?php echo $shipment['shipment_id']; ?></a></td>
                                                    <td><?php echo htmlspecialchars($shipment['to_branch_name']); ?></td>
                                                    <td><?php echo $shipment['total_items'] ?? 0; ?> items</td>
                                                    <td>
                                                        <span class="badge bg-<?php
                                                            echo $shipment['status'] === 'completed' ? 'success' :
                                                                 ($shipment['status'] === 'pending' ? 'warning' :
                                                                  ($shipment['status'] === 'verified' ? 'info' : 'secondary'));
                                                        ?>">
                                                            <?php echo ucfirst($shipment['status']); ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo date('M d, Y', strtotime($shipment['shipment_date'])); ?></td>
                                                    <td><?php echo htmlspecialchars($shipment['created_by_name']); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<footer>
    <p>&copy; <?php echo date('Y'); ?> Inventory Management System. All rights reserved.</p>
</footer>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>

    document.addEventListener('DOMContentLoaded', function() {

        <?php if (!empty($lowStockStats['low_stock_items'])): ?>
        const lowStockCtx = document.getElementById('lowStockChart').getContext('2d');
        const lowStockChart = new Chart(lowStockCtx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode(array_column($lowStockStats['low_stock_items'], 'item_name')); ?>,
                datasets: [{
                    label: 'Stock Count',
                    data: <?php echo json_encode(array_column($lowStockStats['low_stock_items'], 'item_count')); ?>,
                    backgroundColor: 'rgba(220, 53, 69, 0.8)',
                    borderColor: 'rgba(220, 53, 69, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: <?php echo $lowStockStats['low_stock_threshold']; ?>,
                        ticks: {
                            stepSize: 1
                        }
                    }
                },
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const itemName = context.label;
                                const count = context.raw;
                                const threshold = <?php echo $lowStockStats['low_stock_threshold']; ?>;
                                return itemName + ': ' + count + ' units (Threshold: ' + threshold + ')';
                            }
                        }
                    },
                    legend: {
                        display: false
                    }
                }
            }
        });
        <?php endif; ?>

    });
</script>

<?php include '../../includes/footer.php'; ?>
</body>
</html>
