<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Low Stock Alert - FIXED PATH
 * Developer: JOACHIM'S INNOTECH
 */

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

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root from admin/inventory/
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/admin/inventory/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 4);
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define set_flash_message function if it doesn't exist
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

// Define csrf_field function if it doesn't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        $_SESSION['csrf_token'] = $token;
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('inventory.stock.manage');
}

// Set page title
$page_title = 'Low Stock Alert';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

if (!$user_id) {
    header('Location: /HMSPOS/public/login.php');
    exit;
}

// Get filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$category_id = isset($_GET['category_id']) && $_GET['category_id'] !== '' ? (int)$_GET['category_id'] : null;
$outlet_id = isset($_GET['outlet_id']) && $_GET['outlet_id'] !== '' ? (int)$_GET['outlet_id'] : null;
$stock_status = isset($_GET['stock_status']) ? trim($_GET['stock_status']) : 'low';

// Build where clause
$where = "p.stock_item = 1 AND p.is_active = 1";
$params = [];

if ($stock_status === 'low') {
    $where .= " AND p.current_stock <= p.min_stock AND p.current_stock > 0";
} elseif ($stock_status === 'out') {
    $where .= " AND p.current_stock <= 0";
} elseif ($stock_status === 'overstock') {
    $where .= " AND p.max_stock > 0 AND p.current_stock >= p.max_stock";
} elseif ($stock_status === 'all') {
    // No additional condition
}

if (!empty($search)) {
    $where .= " AND (p.product_name LIKE ? OR p.product_code LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term]);
}

if ($category_id) {
    $where .= " AND p.category_id = ?";
    $params[] = $category_id;
}

if ($outlet_id) {
    $where .= " AND p.outlet_id = ?";
    $params[] = $outlet_id;
}

// Get low stock products
$products = [];
if (function_exists('db_fetch_all')) {
    try {
        $products = db_fetch_all("
            SELECT 
                p.*,
                c.category_name,
                o.outlet_name,
                (p.min_stock - p.current_stock) as needed_quantity,
                CASE 
                    WHEN p.current_stock <= 0 THEN 'out'
                    WHEN p.current_stock <= p.min_stock THEN 'low'
                    WHEN p.max_stock > 0 AND p.current_stock >= p.max_stock THEN 'over'
                    ELSE 'normal'
                END as status_level
            FROM pos_products p
            LEFT JOIN pos_categories c ON p.category_id = c.category_id
            LEFT JOIN pos_outlets o ON p.outlet_id = o.outlet_id
            WHERE $where
            ORDER BY 
                CASE 
                    WHEN p.current_stock <= 0 THEN 1
                    WHEN p.current_stock <= p.min_stock THEN 2
                    ELSE 3
                END,
                (p.current_stock / p.min_stock) ASC
        ", $params) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching products: " . $e->getMessage());
    }
}

// Get categories for filter
$categories = [];
if (function_exists('db_fetch_all')) {
    try {
        $categories = db_fetch_all("SELECT category_id, category_name FROM pos_categories WHERE is_active = 1 ORDER BY category_name") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching categories: " . $e->getMessage());
    }
}

// Get outlets for filter
$outlets = [];
if (function_exists('db_fetch_all')) {
    try {
        $outlets = db_fetch_all("SELECT outlet_id, outlet_name FROM pos_outlets WHERE is_active = 1 ORDER BY outlet_name") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching outlets: " . $e->getMessage());
    }
}

// Calculate statistics
$stats = [
    'total_low' => 0,
    'total_out' => 0,
    'total_overstock' => 0,
    'total_normal' => 0
];

if (function_exists('db_fetch_value')) {
    try {
        $stats['total_low'] = db_fetch_value("SELECT COUNT(*) FROM pos_products WHERE stock_item = 1 AND current_stock <= min_stock AND current_stock > 0") ?: 0;
        $stats['total_out'] = db_fetch_value("SELECT COUNT(*) FROM pos_products WHERE stock_item = 1 AND current_stock <= 0") ?: 0;
        $stats['total_overstock'] = db_fetch_value("SELECT COUNT(*) FROM pos_products WHERE stock_item = 1 AND max_stock > 0 AND current_stock >= max_stock") ?: 0;
        $stats['total_normal'] = db_fetch_value("SELECT COUNT(*) FROM pos_products WHERE stock_item = 1 AND current_stock > min_stock") ?: 0;
    } catch (Exception $e) {
        error_log("Error fetching stats: " . $e->getMessage());
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // 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>Low Stock Alert</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; overflow: hidden; color: #fff; }
            .small-box .inner { padding: 20px; }
            .small-box h3 { font-size: 2rem; font-weight: 700; margin: 0 0 10px 0; }
            .small-box p { font-size: 1rem; margin: 0; }
            .small-box .icon { position: absolute; top: 10px; right: 15px; font-size: 4rem; opacity: 0.3; }
            .small-box-footer { display: block; padding: 3px 0; text-align: center; background: rgba(0,0,0,0.1); color: #fff; text-decoration: none; }
            .bg-warning { background-color: #ffc107 !important; }
            .bg-danger { background-color: #dc3545 !important; }
            .bg-success { background-color: #28a745 !important; }
            .bg-info { background-color: #17a2b8 !important; }
            .badge-lg { font-size: 1rem; padding: 0.4rem 0.8rem; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
            .mt-4 { margin-top: 1.5rem; }
            .text-end { text-align: right; }
        </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="#">Low Stock Alert</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="/HMSPOS/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">Low Stock Alert</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/inventory/dashboard.php">Inventory</a></li>
                    <li class="breadcrumb-item"><a href="movements.php">Stock Movements</a></li>
                    <li class="breadcrumb-item active">Low Stock</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['total_low']; ?></h3>
                        <p>Low Stock Items</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                    <a href="?stock_status=low" class="small-box-footer">
                        View <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['total_out']; ?></h3>
                        <p>Out of Stock</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-times-circle"></i>
                    </div>
                    <a href="?stock_status=out" class="small-box-footer">
                        View <i class="fas fa-arrow-circle-right"></i>
                    </a>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['total_normal']; ?></h3>
                        <p>Normal Stock</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['total_overstock']; ?></h3>
                        <p>Overstock</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-arrow-up"></i>
                    </div>
                    <a href="?stock_status=overstock" class="small-box-footer">
                        View <i class="fas fa-arrow-circle-right"></i>
                    </a>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-filter me-1"></i>
                    Filters
                </h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <input type="text" class="form-control" name="search" placeholder="Search products..." 
                               value="<?php echo escape_html($search); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="category_id">
                            <option value="">All Categories</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['category_id'] ?? 0; ?>" <?php echo $category_id == ($cat['category_id'] ?? 0) ? 'selected' : ''; ?>>
                                    <?php echo escape_html($cat['category_name'] ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="outlet_id">
                            <option value="">All Outlets</option>
                            <?php foreach ($outlets as $outlet): ?>
                                <option value="<?php echo $outlet['outlet_id'] ?? 0; ?>" <?php echo $outlet_id == ($outlet['outlet_id'] ?? 0) ? 'selected' : ''; ?>>
                                    <?php echo escape_html($outlet['outlet_name'] ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="stock_status">
                            <option value="low" <?php echo $stock_status == 'low' ? 'selected' : ''; ?>>Low Stock</option>
                            <option value="out" <?php echo $stock_status == 'out' ? 'selected' : ''; ?>>Out of Stock</option>
                            <option value="overstock" <?php echo $stock_status == 'overstock' ? 'selected' : ''; ?>>Overstock</option>
                            <option value="all" <?php echo $stock_status == 'all' ? 'selected' : ''; ?>>All Stock Items</option>
                        </select>
                    </div>
                    
                    <div class="col-md-1">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                    
                    <div class="col-md-1">
                        <a href="?" class="btn btn-secondary w-100">
                            <i class="fas fa-times"></i>
                        </a>
                    </div>
                    
                    <div class="col-md-1 ms-auto">
                        <button type="button" class="btn btn-success w-100" onclick="createPurchaseOrders()">
                            <i class="fas fa-shopping-cart"></i> Order
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Products Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-list me-1"></i>
                    Products
                </h3>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($products)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-check-circle fa-4x mb-3 text-success"></i>
                        <h5>No products found matching the criteria</h5>
                        <p>All stock levels appear to be normal</p>
                    </div>
                <?php else: ?>
                    <form id="bulkActionForm" method="POST" action="../purchases/create-po.php">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                        <?php endif; ?>
                        
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th width="30">
                                            <input type="checkbox" id="selectAll" onchange="toggleAll()">
                                        </th>
                                        <th>Product</th>
                                        <th>Category</th>
                                        <th>Outlet</th>
                                        <th class="text-center">Current Stock</th>
                                        <th class="text-center">Min Stock</th>
                                        <th class="text-center">Max Stock</th>
                                        <th class="text-center">Status</th>
                                        <th class="text-end">Suggested Order</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($products as $product): 
                                        $current_stock = $product['current_stock'] ?? 0;
                                        $min_stock = $product['min_stock'] ?? 0;
                                        $max_stock = $product['max_stock'] ?? 0;
                                        
                                        $status_class = '';
                                        $status_text = '';
                                        
                                        if ($current_stock <= 0) {
                                            $status_class = 'danger';
                                            $status_text = 'Out of Stock';
                                        } elseif ($current_stock <= $min_stock) {
                                            $status_class = 'warning';
                                            $status_text = 'Low Stock';
                                        } elseif ($max_stock > 0 && $current_stock >= $max_stock) {
                                            $status_class = 'info';
                                            $status_text = 'Overstock';
                                        } else {
                                            $status_class = 'success';
                                            $status_text = 'Normal';
                                        }
                                        
                                        $suggested_order = max(0, ($min_stock * 2) - $current_stock);
                                    ?>
                                    <tr class="<?php echo $status_class == 'danger' ? 'table-danger' : ($status_class == 'warning' ? 'table-warning' : ''); ?>">
                                        <td>
                                            <?php if ($current_stock <= $min_stock): ?>
                                                <input type="checkbox" name="product_ids[]" value="<?php echo $product['product_id'] ?? 0; ?>" class="product-checkbox">
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a href="/HMSPOS/pos/products/view.php?id=<?php echo $product['product_id'] ?? 0; ?>">
                                                <strong><?php echo escape_html($product['product_name'] ?? ''); ?></strong>
                                            </a>
                                            <br>
                                            <small class="text-muted"><?php echo escape_html($product['product_code'] ?? ''); ?></small>
                                        </td>
                                        <td><?php echo escape_html($product['category_name'] ?? ''); ?></td>
                                        <td><?php echo escape_html($product['outlet_name'] ?? 'All'); ?></td>
                                        <td class="text-center">
                                            <span class="badge bg-<?php echo $status_class; ?> badge-lg">
                                                <?php echo $current_stock; ?> <?php echo escape_html($product['unit_of_measure'] ?? ''); ?>
                                            </span>
                                        </td>
                                        <td class="text-center"><?php echo $min_stock; ?></td>
                                        <td class="text-center"><?php echo $max_stock ?: '∞'; ?></td>
                                        <td class="text-center">
                                            <span class="badge bg-<?php echo $status_class; ?>">
                                                <?php echo $status_text; ?>
                                            </span>
                                        </td>
                                        <td class="text-end">
                                            <?php if ($suggested_order > 0): ?>
                                                <span class="badge bg-info"><?php echo $suggested_order; ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($current_stock <= $min_stock): ?>
                                                <a href="../purchases/create-po.php?product_id=<?php echo $product['product_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-success">
                                                    <i class="fas fa-shopping-cart"></i> Order
                                                </a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
            
            <?php if (!empty($products)): ?>
            <div class="card-footer">
                <div class="row">
                    <div class="col-md-6">
                        <span id="selectedCount">0</span> product(s) selected
                    </div>
                    <div class="col-md-6 text-end">
                        <button type="button" class="btn btn-sm btn-success" onclick="createPO()">
                            <i class="fas fa-shopping-cart"></i> Create Purchase Order for Selected
                        </button>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Reorder Suggestions -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-lightbulb me-1"></i>
                            Reorder Suggestions
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-warning elevation-1">
                                        <i class="fas fa-clock"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Immediate Reorder</span>
                                        <span class="info-box-number"><?php echo $stats['total_low']; ?> items</span>
                                        <span class="info-box-text">Below minimum stock</span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-danger elevation-1">
                                        <i class="fas fa-ban"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Critical</span>
                                        <span class="info-box-number"><?php echo $stats['total_out']; ?> items</span>
                                        <span class="info-box-text">Out of stock</span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-info elevation-1">
                                        <i class="fas fa-calculator"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Suggested Order Total</span>
                                        <span class="info-box-number">
                                            <?php 
                                            $total_suggested = 0;
                                            foreach ($products as $p) {
                                                $current = $p['current_stock'] ?? 0;
                                                $min = $p['min_stock'] ?? 0;
                                                if ($current <= $min) {
                                                    $total_suggested += max(0, ($min * 2) - $current);
                                                }
                                            }
                                            echo $total_suggested;
                                            ?>
                                        </span>
                                        <span class="info-box-text">units to order</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
let selectedProducts = new Set();

$(document).ready(function() {
    updateSelectedCount();
});

function toggleAll() {
    const checked = $('#selectAll').prop('checked');
    $('.product-checkbox').each(function() {
        $(this).prop('checked', checked);
        const productId = $(this).val();
        if (checked) {
            selectedProducts.add(productId);
        } else {
            selectedProducts.delete(productId);
        }
    });
    updateSelectedCount();
}

$('.product-checkbox').on('change', function() {
    const productId = $(this).val();
    if ($(this).prop('checked')) {
        selectedProducts.add(productId);
    } else {
        selectedProducts.delete(productId);
    }
    updateSelectAll();
    updateSelectedCount();
});

function updateSelectAll() {
    const total = $('.product-checkbox').length;
    const checked = $('.product-checkbox:checked').length;
    
    if (total > 0 && checked === total) {
        $('#selectAll').prop('checked', true).prop('indeterminate', false);
    } else if (checked > 0) {
        $('#selectAll').prop('checked', false).prop('indeterminate', true);
    } else {
        $('#selectAll').prop('checked', false).prop('indeterminate', false);
    }
}

function updateSelectedCount() {
    const count = selectedProducts.size;
    $('#selectedCount').text(count);
}

function createPO() {
    const selected = Array.from(selectedProducts);
    
    if (selected.length === 0) {
        alert('Please select at least one product');
        return;
    }
    
    // Create hidden inputs for selected products
    selected.forEach(id => {
        $('#bulkActionForm').append(`<input type="hidden" name="bulk_products[]" value="${id}">`);
    });
    
    $('#bulkActionForm').submit();
}

function createPurchaseOrders() {
    if (selectedProducts.size > 0) {
        createPO();
    } else {
        window.location.href = '../purchases/create-po.php';
    }
}
</script>

<style>
.badge-lg {
    font-size: 1rem;
    padding: 0.4rem 0.8rem;
}
.info-box {
    box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2);
    border-radius: 0.25rem;
    background: #fff;
    display: flex;
    margin-bottom: 20px;
    min-height: 80px;
}
.info-box-icon {
    border-radius: 0.25rem 0 0 0.25rem;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 70px;
    font-size: 1.875rem;
    text-align: center;
}
.info-box-content {
    padding: 10px;
    flex: 1;
}
.bg-light { background-color: #f8f9fa !important; }
</style>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>