<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Inventory Dashboard - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct base path
$base_path = null;

// Current file: /Applications/XAMPP/xamppfiles/htdocs/HMSPOS/inventory/dashboard.php
// We need to go up to: /Applications/XAMPP/xamppfiles/htdocs/HMSPOS/

// Method 1: Try going up 2 levels (from dashboard.php to HMSPOS)
$base_path = dirname(__DIR__, 2);

// Method 2: Manual calculation if method 1 fails
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = dirname(dirname(__DIR__));
}

// Method 3: Absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try relative path from document root
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = $_SERVER['DOCUMENT_ROOT'] . '/HMSPOS';
}

// Verify the base path works
if (!file_exists($base_path . '/config/config.php')) {
    die("Error: Cannot find system files. Tried: " . $base_path . "/config/config.php");
}

// Initialize system
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/constants.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/helpers.php';
require_once $base_path . '/config/auth.php';

// Load csrf if it exists
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}

// Define helper functions if they don't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        return '<input type="hidden" name="csrf_token" value="' . csrf_token() . '">';
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token() {
        return session_id() . '-' . time();
    }
}

if (!function_exists('base_url')) {
    function base_url($path = '') {
        // Remove any leading slash from path
        $path = ltrim($path, '/');
        // Return the full URL
        return '/HMSPOS/' . $path;
    }
}

if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('format_currency')) {
    function format_currency($amount) {
        $symbol = defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF';
        return $symbol . ' ' . number_format($amount, 0);
    }
}

if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        $timestamp = strtotime($date);
        return $timestamp ? date($format, $timestamp) : $date;
    }
}

if (!function_exists('time_ago')) {
    function time_ago($timestamp) {
        if (empty($timestamp)) return 'Unknown';
        
        $time_ago = strtotime($timestamp);
        $current_time = time();
        $time_difference = $current_time - $time_ago;
        $seconds = $time_difference;
        
        $minutes = round($seconds / 60);
        $hours = round($seconds / 3600);
        $days = round($seconds / 86400);
        $weeks = round($seconds / 604800);
        $months = round($seconds / 2629440);
        $years = round($seconds / 31553280);
        
        if ($seconds <= 60) {
            return "Just Now";
        } else if ($minutes <= 60) {
            return ($minutes == 1) ? "1 minute ago" : "$minutes minutes ago";
        } else if ($hours <= 24) {
            return ($hours == 1) ? "1 hour ago" : "$hours hours ago";
        } else if ($days <= 7) {
            return ($days == 1) ? "yesterday" : "$days days ago";
        } else if ($weeks <= 4.3) {
            return ($weeks == 1) ? "1 week ago" : "$weeks weeks ago";
        } else if ($months <= 12) {
            return ($months == 1) ? "1 month ago" : "$months months ago";
        } else {
            return ($years == 1) ? "1 year ago" : "$years years ago";
        }
    }
}

// Require authentication and permission
require_auth();

// Check if permission function exists
if (function_exists('require_permission')) {
    require_permission('dashboard.inventory');
}

// Set page title
$page_title = 'Inventory Dashboard';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;

// Initialize stats with default values
$stats = [
    'total_products' => 0,
    'stock_items' => 0,
    'low_stock' => 0,
    'out_of_stock' => 0,
    'total_suppliers' => 0,
    'active_purchase_orders' => 0,
    'pending_receiving' => 0,
    'total_stock_value' => 0,
    'monthly_consumption' => 0,
    'turnover_rate' => 0
];

// Initialize empty arrays for data
$low_stock_items = [];
$recent_movements = [];
$active_pos = [];
$category_stock = [];
$top_suppliers = [];
$reorder_list = [];
$value_trend = ['labels' => [], 'data' => []];

try {
    // Check if tables exist
    $pos_products_exists = db_fetch_value("SHOW TABLES LIKE 'pos_products'");
    $pos_categories_exists = db_fetch_value("SHOW TABLES LIKE 'pos_categories'");
    $suppliers_exists = db_fetch_value("SHOW TABLES LIKE 'suppliers'");
    $purchase_orders_exists = db_fetch_value("SHOW TABLES LIKE 'purchase_orders'");
    $stock_movements_exists = db_fetch_value("SHOW TABLES LIKE 'stock_movements'");
    $pos_sale_items_exists = db_fetch_value("SHOW TABLES LIKE 'pos_sale_items'");
    $pos_sales_exists = db_fetch_value("SHOW TABLES LIKE 'pos_sales'");

    // Get inventory statistics
    if ($pos_products_exists) {
        $stats['total_products'] = (int)(db_fetch_value("
            SELECT COUNT(*) FROM pos_products WHERE is_active = 1
        ") ?: 0);
        
        $stats['stock_items'] = (int)(db_fetch_value("
            SELECT COUNT(*) FROM pos_products WHERE stock_item = 1 AND is_active = 1
        ") ?: 0);
        
        $stats['low_stock'] = (int)(db_fetch_value("
            SELECT COUNT(*) FROM pos_products 
            WHERE stock_item = 1 
            AND current_stock <= min_stock
            AND is_active = 1
        ") ?: 0);
        
        $stats['out_of_stock'] = (int)(db_fetch_value("
            SELECT COUNT(*) FROM pos_products 
            WHERE stock_item = 1 
            AND current_stock <= 0
            AND is_active = 1
        ") ?: 0);
        
        $stats['total_stock_value'] = (float)(db_fetch_value("
            SELECT COALESCE(SUM(current_stock * cost_price), 0) 
            FROM pos_products 
            WHERE stock_item = 1 AND is_active = 1
        ") ?: 0);
    }
    
    if ($suppliers_exists) {
        $stats['total_suppliers'] = (int)(db_fetch_value("
            SELECT COUNT(*) FROM suppliers WHERE is_active = 1
        ") ?: 0);
    }
    
    if ($purchase_orders_exists) {
        $stats['active_purchase_orders'] = (int)(db_fetch_value("
            SELECT COUNT(*) FROM purchase_orders 
            WHERE status IN ('ordered', 'partial')
        ") ?: 0);
        
        $stats['pending_receiving'] = (int)(db_fetch_value("
            SELECT COUNT(*) FROM purchase_orders 
            WHERE status = 'ordered'
        ") ?: 0);
    }
    
    if ($pos_sale_items_exists && $pos_sales_exists && $pos_products_exists) {
        $stats['monthly_consumption'] = (float)(db_fetch_value("
            SELECT COALESCE(SUM(si.quantity * p.cost_price), 0)
            FROM pos_sale_items si
            JOIN pos_products p ON si.product_id = p.product_id
            JOIN pos_sales s ON si.sale_id = s.sale_id
            WHERE s.sale_time >= DATE_SUB(NOW(), INTERVAL 30 DAY)
            AND p.stock_item = 1
        ") ?: 0);
    }
    
    // Calculate turnover rate (annualized)
    $stats['turnover_rate'] = $stats['total_stock_value'] > 0 
        ? round(($stats['monthly_consumption'] * 12) / $stats['total_stock_value'], 2)
        : 0;

    // Get low stock items
    if ($pos_products_exists && $pos_categories_exists) {
        $low_stock_items = db_fetch_all("
            SELECT 
                p.product_id, p.product_name, p.product_code,
                p.current_stock, p.min_stock, p.max_stock,
                c.category_name,
                (p.current_stock / p.min_stock) as stock_ratio
            FROM pos_products p
            JOIN pos_categories c ON p.category_id = c.category_id
            WHERE p.stock_item = 1 
            AND p.current_stock <= p.min_stock
            AND p.is_active = 1
            ORDER BY stock_ratio ASC
            LIMIT 20
        ") ?: [];
    }

    // Get recent stock movements
    if ($stock_movements_exists && $pos_products_exists) {
        $recent_movements = db_fetch_all("
            SELECT 
                sm.*,
                p.product_name, p.product_code,
                u.first_name, u.last_name
            FROM stock_movements sm
            JOIN pos_products p ON sm.product_id = p.product_id
            LEFT JOIN users u ON sm.created_by = u.user_id
            ORDER BY sm.created_at DESC
            LIMIT 20
        ") ?: [];
    }

    // Get active purchase orders
    if ($purchase_orders_exists && $suppliers_exists) {
        $active_pos = db_fetch_all("
            SELECT 
                po.*,
                s.supplier_name,
                u.first_name, u.last_name
            FROM purchase_orders po
            JOIN suppliers s ON po.supplier_id = s.supplier_id
            LEFT JOIN users u ON po.created_by = u.user_id
            WHERE po.status IN ('ordered', 'partial')
            ORDER BY po.expected_date ASC
            LIMIT 15
        ") ?: [];
    }

    // Get category stock distribution
    if ($pos_categories_exists && $pos_products_exists) {
        $category_stock = db_fetch_all("
            SELECT 
                c.category_id, c.category_name,
                COUNT(p.product_id) as product_count,
                SUM(p.current_stock) as total_units,
                COALESCE(SUM(p.current_stock * p.cost_price), 0) as stock_value
            FROM pos_categories c
            LEFT JOIN pos_products p ON c.category_id = p.category_id AND p.stock_item = 1
            WHERE c.is_active = 1
            GROUP BY c.category_id
            ORDER BY stock_value DESC
        ") ?: [];
    }

    // Get top suppliers by purchase volume
    if ($suppliers_exists && $purchase_orders_exists) {
        $top_suppliers = db_fetch_all("
            SELECT 
                s.supplier_id, s.supplier_name,
                COUNT(po.po_id) as order_count,
                COALESCE(SUM(po.total_amount), 0) as total_spent,
                MAX(po.order_date) as last_order
            FROM suppliers s
            LEFT JOIN purchase_orders po ON s.supplier_id = po.supplier_id
            WHERE s.is_active = 1
            GROUP BY s.supplier_id
            ORDER BY total_spent DESC
            LIMIT 10
        ") ?: [];
    }

    // Get monthly stock value trend
    for ($i = 5; $i >= 0; $i--) {
        $month = date('Y-m', strtotime("-$i months"));
        $month_name = date('M Y', strtotime("-$i months"));
        
        // This is a simplified calculation - in production you'd need proper inventory valuation
        $value = (float)(db_fetch_value("
            SELECT COALESCE(SUM(p.current_stock * p.cost_price), 0)
            FROM pos_products p
            WHERE p.stock_item = 1
        ") ?: 0);
        
        $value_trend['labels'][] = $month_name;
        $value_trend['data'][] = $value;
    }

    // Get products needing reorder (below min stock)
    if ($pos_products_exists && $pos_categories_exists) {
        $reorder_list = db_fetch_all("
            SELECT 
                p.product_id, p.product_name, p.product_code,
                p.current_stock, p.min_stock,
                c.category_name,
                s.supplier_name
            FROM pos_products p
            JOIN pos_categories c ON p.category_id = c.category_id
            LEFT JOIN purchase_orders po ON p.product_id IN (
                SELECT product_id FROM purchase_order_items WHERE po_id IN (
                    SELECT po_id FROM purchase_orders WHERE status IN ('ordered', 'partial')
                )
            )
            LEFT JOIN suppliers s ON po.supplier_id = s.supplier_id
            WHERE p.stock_item = 1 
            AND p.current_stock <= p.min_stock
            AND p.is_active = 1
            ORDER BY (p.current_stock / p.min_stock) ASC
            LIMIT 15
        ") ?: [];
    }

} catch (Exception $e) {
    error_log("Error in inventory dashboard: " . $e->getMessage());
}

// Include header - check multiple possible locations
$header_paths = [
    $base_path . '/views/partials/header.php',
    $base_path . '/includes/header.php'
];

$header_found = false;
foreach ($header_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $header_found = true;
        break;
    }
}

if (!$header_found) {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Inventory Dashboard</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .small-box { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; position: relative; display: block; }
            .small-box > .inner { padding: 10px; }
            .small-box h3 { font-size: 2.2rem; font-weight: bold; margin: 0 0 10px 0; white-space: nowrap; padding: 0; }
            .small-box p { font-size: 1rem; }
            .small-box .icon { position: absolute; top: 10px; right: 10px; z-index: 0; font-size: 70px; color: rgba(0,0,0,0.15); }
            .info-box { box-shadow: 0 0 1px rgba(0,0,0,0.125), 0 1px 3px rgba(0,0,0,0.2); border-radius: 0.5rem; background: #fff; display: flex; align-items: stretch; margin-bottom: 15px; min-height: 90px; }
            .info-box-icon { border-radius: 0.5rem 0 0 0.5rem; display: flex; align-items: center; justify-content: center; width: 90px; font-size: 2.5rem; }
            .info-box-content { padding: 10px; flex: 1; }
            .badge { padding: 5px 10px; border-radius: 4px; }
            .badge-success { background-color: #28a745; color: #fff; }
            .badge-warning { background-color: #ffc107; color: #000; }
            .badge-danger { background-color: #dc3545; color: #fff; }
            .badge-info { background-color: #17a2b8; color: #fff; }
            .badge-secondary { background-color: #6c757d; color: #fff; }
            .progress-xs { height: 5px; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Ruhondo Beach Resort</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="<?php echo base_url('public/logout.php'); ?>">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Inventory Dashboard</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('public/dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item active">Inventory Dashboard</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Quick Actions Row -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Quick Actions</h3>
                    </div>
                    <div class="card-body">
                        <a href="<?php echo base_url('/purchases/create-po.php'); ?>" class="btn btn-primary mr-2 mb-2">
                            <i class="fas fa-plus-circle mr-1"></i> New Purchase Order
                        </a>
                        <a href="<?php echo base_url('/purchases/receive.php'); ?>" class="btn btn-success mr-2 mb-2">
                            <i class="fas fa-truck mr-1"></i> Receive Stock
                        </a>
                        <a href="<?php echo base_url('/stock/adjustments.php'); ?>" class="btn btn-warning mr-2 mb-2">
                            <i class="fas fa-balance-scale mr-1"></i> Stock Adjustment
                        </a>
                        <a href="<?php echo base_url('/stock/transfers.php'); ?>" class="btn btn-info mr-2 mb-2">
                            <i class="fas fa-exchange-alt mr-1"></i> Transfer Stock
                        </a>
                        <a href="<?php echo base_url('/suppliers/index.php'); ?>" class="btn btn-secondary mr-2 mb-2">
                            <i class="fas fa-truck mr-1"></i> Suppliers
                        </a>
                        <a href="<?php echo base_url('/stock/low-stock.php'); ?>" class="btn btn-danger mr-2 mb-2">
                            <i class="fas fa-exclamation-triangle mr-1"></i> Low Stock Alert
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['total_products']; ?></h3>
                        <p>Total Products</p>
                        <small><?php echo $stats['stock_items']; ?> stock items</small>
                    </div>
                    <div class="icon">
                        <i class="fas fa-boxes"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['total_stock_value']); ?></h3>
                        <p>Stock Value</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['low_stock']; ?></h3>
                        <p>Low Stock Items</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                    <a href="#low-stock" class="small-box-footer">
                        View Details <i class="fas fa-arrow-circle-right"></i>
                    </a>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $stats['active_purchase_orders']; ?></h3>
                        <p>Active POs</p>
                        <small><?php echo $stats['pending_receiving']; ?> to receive</small>
                    </div>
                    <div class="icon">
                        <i class="fas fa-clipboard-list"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Second Row Stats -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <span class="info-box-icon bg-info"><i class="fas fa-truck"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Total Suppliers</span>
                        <span class="info-box-number"><?php echo $stats['total_suppliers']; ?></span>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <span class="info-box-icon bg-success"><i class="fas fa-chart-line"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Turnover Rate</span>
                        <span class="info-box-number"><?php echo $stats['turnover_rate']; ?>x</span>
                        <span class="info-box-text">(annualized)</span>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <span class="info-box-icon bg-warning"><i class="fas fa-calendar"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Monthly Consumption</span>
                        <span class="info-box-number"><?php echo format_currency($stats['monthly_consumption']); ?></span>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <span class="info-box-icon bg-danger"><i class="fas fa-times-circle"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Out of Stock</span>
                        <span class="info-box-number"><?php echo $stats['out_of_stock']; ?></span>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Stock Value Chart -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-line mr-1"></i>
                            Stock Value Trend
                        </h3>
                    </div>
                    <div class="card-body">
                        <?php if (empty($value_trend['labels'])): ?>
                            <div class="text-center text-muted py-4">
                                <p>No data available for chart</p>
                            </div>
                        <?php else: ?>
                            <canvas id="stockValueChart" style="height: 300px;"></canvas>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Category Distribution -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-pie mr-1"></i>
                            Stock Value by Category
                        </h3>
                    </div>
                    <div class="card-body">
                        <?php if (empty($category_stock)): ?>
                            <div class="text-center text-muted py-4">
                                <p>No category data available</p>
                            </div>
                        <?php else: ?>
                            <canvas id="categoryChart" style="height: 300px;"></canvas>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Low Stock Items -->
            <div class="col-md-6" id="low-stock">
                <div class="card card-danger">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-exclamation-triangle mr-1"></i>
                            Low Stock Items
                        </h3>
                        <div class="card-tools">
                            <a href="<?php echo base_url('/stock/low-stock.php'); ?>" class="btn btn-sm btn-danger">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($low_stock_items)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-check-circle fa-3x mb-3 text-success"></i>
                                <p>No low stock items</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Product</th>
                                            <th>Category</th>
                                            <th class="text-center">Stock</th>
                                            <th class="text-center">Min</th>
                                            <th>Status</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($low_stock_items as $item): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo escape_html($item['product_name']); ?></strong>
                                                <br>
                                                <small><?php echo $item['product_code']; ?></small>
                                            </td>
                                            <td><?php echo escape_html($item['category_name']); ?></td>
                                            <td class="text-center"><?php echo $item['current_stock']; ?></td>
                                            <td class="text-center"><?php echo $item['min_stock']; ?></td>
                                            <td>
                                                <?php 
                                                $percentage = $item['min_stock'] > 0 
                                                    ? ($item['current_stock'] / $item['min_stock']) * 100 
                                                    : 0;
                                                $progress_class = $percentage <= 25 ? 'danger' : ($percentage <= 50 ? 'warning' : 'info');
                                                ?>
                                                <div class="progress progress-xs">
                                                    <div class="progress-bar bg-<?php echo $progress_class; ?>" 
                                                         style="width: <?php echo min(100, $percentage); ?>%"></div>
                                                </div>
                                                <small><?php echo round($percentage); ?>% of min</small>
                                            </td>
                                            <td>
                                                <a href="<?php echo base_url('/purchases/create-po.php?product_id=' . $item['product_id']); ?>" 
                                                   class="btn btn-sm btn-primary">
                                                    <i class="fas fa-shopping-cart"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Active Purchase Orders -->
            <div class="col-md-6">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-clipboard-list mr-1"></i>
                            Active Purchase Orders
                        </h3>
                        <div class="card-tools">
                            <a href="<?php echo base_url('/purchases/index.php?status=ordered,partial'); ?>" class="btn btn-sm btn-info">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($active_pos)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-clipboard-list fa-3x mb-3"></i>
                                <p>No active purchase orders</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>PO Number</th>
                                            <th>Supplier</th>
                                            <th>Order Date</th>
                                            <th>Expected</th>
                                            <th>Status</th>
                                            <th class="text-right">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($active_pos as $po): ?>
                                        <tr>
                                            <td>
                                                <a href="<?php echo base_url('/purchases/view.php?id=' . $po['po_id']); ?>">
                                                    <?php echo $po['po_number']; ?>
                                                </a>
                                            </td>
                                            <td><?php echo escape_html($po['supplier_name']); ?></td>
                                            <td><?php echo format_date($po['order_date']); ?></td>
                                            <td>
                                                <?php 
                                                if ($po['expected_date']) {
                                                    $days = (strtotime($po['expected_date']) - time()) / 86400;
                                                    if ($days < 0) {
                                                        echo '<span class="badge badge-danger">Overdue</span>';
                                                    } else {
                                                        echo format_date($po['expected_date']);
                                                    }
                                                } else {
                                                    echo '-';
                                                }
                                                ?>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $po['status'] == 'ordered' ? 'info' : 
                                                        ($po['status'] == 'partial' ? 'warning' : 
                                                        ($po['status'] == 'received' ? 'success' : 'secondary'));
                                                ?>">
                                                    <?php echo ucfirst($po['status']); ?>
                                                </span>
                                            </td>
                                            <td class="text-right"><?php echo format_currency($po['total_amount']); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Recent Stock Movements -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history mr-1"></i>
                            Recent Stock Movements
                        </h3>
                        <div class="card-tools">
                            <a href="<?php echo base_url('/stock/movements.php'); ?>" class="btn btn-sm btn-primary">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($recent_movements)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-exchange-alt fa-3x mb-3"></i>
                                <p>No stock movements recorded</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Time</th>
                                            <th>Product</th>
                                            <th>Type</th>
                                            <th class="text-center">Qty</th>
                                            <th>Reference</th>
                                            <th>By</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent_movements as $movement): ?>
                                        <tr>
                                            <td><?php echo time_ago($movement['created_at']); ?></td>
                                            <td>
                                                <strong><?php echo escape_html($movement['product_name']); ?></strong>
                                                <br>
                                                <small><?php echo $movement['product_code']; ?></small>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $movement['movement_type'] == 'purchase' ? 'success' : 
                                                        ($movement['movement_type'] == 'sale' ? 'info' : 
                                                        ($movement['movement_type'] == 'adjustment' ? 'warning' : 
                                                        ($movement['movement_type'] == 'transfer_out' ? 'danger' : 'secondary')));
                                                ?>">
                                                    <?php echo ucfirst(str_replace('_', ' ', $movement['movement_type'])); ?>
                                                </span>
                                            </td>
                                            <td class="text-center">
                                                <span class="badge badge-<?php echo $movement['quantity'] > 0 ? 'success' : 'danger'; ?>">
                                                    <?php echo $movement['quantity'] > 0 ? '+' : ''; ?><?php echo $movement['quantity']; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if ($movement['reference_type']): ?>
                                                    <small><?php echo $movement['reference_type']; ?> #<?php echo $movement['reference_id']; ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <small><?php echo escape_html($movement['first_name']); ?></small>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Top Suppliers -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-trophy mr-1"></i>
                            Top Suppliers by Purchase Volume
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($top_suppliers)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-truck fa-3x mb-3"></i>
                                <p>No supplier data available</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Supplier</th>
                                            <th class="text-center">Orders</th>
                                            <th class="text-right">Total Spent</th>
                                            <th>Last Order</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($top_suppliers as $index => $supplier): ?>
                                        <tr>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $index == 0 ? 'warning' : ($index == 1 ? 'secondary' : 'light');
                                                ?> mr-2">#<?php echo $index + 1; ?></span>
                                                <a href="<?php echo base_url('/suppliers/view.php?id=' . $supplier['supplier_id']); ?>">
                                                    <?php echo escape_html($supplier['supplier_name']); ?>
                                                </a>
                                            </td>
                                            <td class="text-center"><?php echo $supplier['order_count']; ?></td>
                                            <td class="text-right"><?php echo format_currency($supplier['total_spent']); ?></td>
                                            <td>
                                                <?php echo $supplier['last_order'] ? format_date($supplier['last_order']) : 'Never'; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Reorder Recommendations -->
        <?php if (!empty($reorder_list)): ?>
        <div class="row">
            <div class="col-12">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-shopping-cart mr-1"></i>
                            Reorder Recommendations
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th>Category</th>
                                        <th class="text-center">Current Stock</th>
                                        <th class="text-center">Min Stock</th>
                                        <th class="text-center">Suggested Order</th>
                                        <th>Preferred Supplier</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($reorder_list as $item): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo escape_html($item['product_name']); ?></strong>
                                            <br>
                                            <small><?php echo $item['product_code']; ?></small>
                                        </td>
                                        <td><?php echo escape_html($item['category_name']); ?></td>
                                        <td class="text-center"><?php echo $item['current_stock']; ?></td>
                                        <td class="text-center"><?php echo $item['min_stock']; ?></td>
                                        <td class="text-center">
                                            <?php 
                                            $suggested = max($item['min_stock'] * 2 - $item['current_stock'], $item['min_stock']);
                                            echo $suggested;
                                            ?>
                                        </td>
                                        <td>
                                            <?php echo escape_html($item['supplier_name'] ?? 'No preferred supplier'); ?>
                                        </td>
                                        <td>
                                            <a href="<?php echo base_url('/purchases/create-po.php?product_id=' . $item['product_id']); ?>" 
                                               class="btn btn-sm btn-primary">
                                                <i class="fas fa-shopping-cart"></i> Create PO
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</section>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js"></script>

<script>
$(document).ready(function() {
    <?php if (!empty($value_trend['labels'])): ?>
    // Stock Value Chart
    const valueCtx = document.getElementById('stockValueChart').getContext('2d');
    
    new Chart(valueCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($value_trend['labels']); ?>,
            datasets: [{
                label: 'Stock Value',
                data: <?php echo json_encode($value_trend['data']); ?>,
                borderColor: '#28a745',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                tension: 0.1,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value, index, values) {
                            return '<?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?>' + value;
                        }
                    }
                }
            }
        }
    });
    <?php endif; ?>
    
    <?php
    $cat_labels = [];
    $cat_values = [];
    $cat_colors = [];
    $color_palette = ['#007bff', '#28a745', '#ffc107', '#dc3545', '#17a2b8', '#6c757d', '#6610f2', '#e83e8c'];
    
    foreach ($category_stock as $index => $cat) {
        if ($cat['stock_value'] > 0) {
            $cat_labels[] = $cat['category_name'];
            $cat_values[] = $cat['stock_value'];
            $cat_colors[] = $color_palette[$index % count($color_palette)];
        }
    }
    
    if (!empty($cat_labels)):
    ?>
    
    // Category Distribution Chart
    const categoryCtx = document.getElementById('categoryChart').getContext('2d');
    
    new Chart(categoryCtx, {
        type: 'doughnut',
        data: {
            labels: <?php echo json_encode($cat_labels); ?>,
            datasets: [{
                data: <?php echo json_encode($cat_values); ?>,
                backgroundColor: <?php echo json_encode($cat_colors); ?>,
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    <?php endif; ?>
});

// Auto-refresh every 5 minutes
setTimeout(function() {
    location.reload();
}, 300000);
</script>

<style>
.badge-light {
    background-color: #f8f9fa;
    color: #212529;
}
.badge.bronze {
    background-color: #cd7f32;
    color: white;
}
.progress-xs {
    height: 5px;
}
.mr-1 { margin-right: 0.25rem; }
.mr-2 { margin-right: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mb-4 { margin-bottom: 1.5rem; }
.mt-2 { margin-top: 0.5rem; }
.text-center { text-align: center; }
.text-right { text-align: right; }
.text-muted { color: #6c757d; }
</style>

<?php
// Include footer - check multiple possible locations
$footer_paths = [
    $base_path . '/views/partials/footer.php',
    $base_path . '/includes/footer.php'
];

$footer_found = false;
foreach ($footer_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $footer_found = true;
        break;
    }
}

if (!$footer_found) {
    echo '</div></div></body></html>';
}
?>