<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Products Management - List View - WITH DELETE BUTTON (Connection Fixed)
 * Developer: JOACHIM'S INNOTECH
 */

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

// Load the universal initializer (go up two levels from /pos/products/ to root)
require_once dirname(dirname(__DIR__)) . '/config/init.php';

// Require authentication
require_auth();

// 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
    }
}

// Get database connection - TRY MULTIPLE METHODS
$db = null;

// Method 1: Try global $pdo
global $pdo;
if (isset($pdo) && $pdo instanceof PDO) {
    $db = $pdo;
    error_log("Using global \$pdo connection");
}

// Method 2: Try global $db (maybe it's a PDO object)
if (!$db) {
    global $db_global;
    if (isset($db_global) && $db_global instanceof PDO) {
        $db = $db_global;
        error_log("Using global \$db_global connection");
    }
}

// Method 3: Try database function from your system
if (!$db && function_exists('db_connect')) {
    $db = db_connect();
    error_log("Using db_connect() function");
}

// Method 4: Try to get from registry or container
if (!$db && function_exists('app')) {
    $db = app('db');
    error_log("Using app('db')");
}

// Method 5: Create new connection as last resort
if (!$db) {
    try {
        // Try to include config and create connection
        if (file_exists(dirname(dirname(__DIR__)) . '/config/database.php')) {
            require_once dirname(dirname(__DIR__)) . '/config/database.php';
            
            // Check if DB constants are defined
            if (defined('DB_HOST') && defined('DB_NAME') && defined('DB_USER') && defined('DB_PASS')) {
                $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
                $options = [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false
                ];
                $db = new PDO($dsn, DB_USER, DB_PASS, $options);
                error_log("Created new PDO connection using constants");
            }
        }
    } catch (Exception $e) {
        error_log("Failed to create database connection: " . $e->getMessage());
    }
}

// If still no connection, show error
if (!$db) {
    die("Database connection could not be established. Please check your configuration.");
}

// Handle delete action
if (isset($_GET['delete']) && isset($_GET['id']) && is_numeric($_GET['id'])) {
    $product_id = (int)$_GET['id'];
    
    // Store current GET parameters for redirect (excluding delete and id)
    $redirect_params = $_GET;
    unset($redirect_params['delete']);
    unset($redirect_params['id']);
    $redirect_query = http_build_query($redirect_params);
    
    try {
        // Check if product has sales
        $stmt = $db->prepare("SELECT COUNT(*) FROM pos_sale_items WHERE product_id = ?");
        $stmt->execute([$product_id]);
        $sales_count = $stmt->fetchColumn();
        
        if ($sales_count > 0) {
            // Product has sales - just deactivate instead of deleting
            $stmt = $db->prepare("UPDATE pos_products SET is_active = 0 WHERE product_id = ?");
            $stmt->execute([$product_id]);
            $message = "Product has sales history and was deactivated instead of deleted.";
            $type = 'warning';
            
            // Log the action
            error_log("Product ID $product_id deactivated (had $sales_count sales)");
        } else {
            // No sales - can delete permanently
            // First check if product exists in other tables (inventory, etc.)
            $tables_to_check = ['pos_inventory', 'inventory', 'product_stock'];
            $has_other_records = false;
            
            foreach ($tables_to_check as $table) {
                // Check if table exists
                try {
                    $stmt = $db->query("SHOW TABLES LIKE '$table'");
                    if ($stmt->rowCount() > 0) {
                        $stmt = $db->prepare("SELECT COUNT(*) FROM $table WHERE product_id = ?");
                        $stmt->execute([$product_id]);
                        if ($stmt->fetchColumn() > 0) {
                            $has_other_records = true;
                            break;
                        }
                    }
                } catch (Exception $e) {
                    // Table doesn't exist, continue
                    continue;
                }
            }
            
            if ($has_other_records) {
                // Has records in other tables - deactivate instead
                $stmt = $db->prepare("UPDATE pos_products SET is_active = 0 WHERE product_id = ?");
                $stmt->execute([$product_id]);
                $message = "Product has related records and was deactivated instead of deleted.";
                $type = 'warning';
            } else {
                // Safe to delete
                $stmt = $db->prepare("DELETE FROM pos_products WHERE product_id = ?");
                $stmt->execute([$product_id]);
                $message = "Product deleted successfully.";
                $type = 'success';
            }
        }
        
        // Set flash message if function exists
        if (function_exists('set_flash_message')) {
            set_flash_message($message, $type);
        } else {
            // Fallback to session flash
            session_start();
            $_SESSION['flash_message'] = $message;
            $_SESSION['flash_type'] = $type;
        }
        
    } catch (Exception $e) {
        error_log("Error deleting product: " . $e->getMessage());
        $message = "Error deleting product: " . $e->getMessage();
        $type = 'danger';
        
        if (function_exists('set_flash_message')) {
            set_flash_message($message, $type);
        } else {
            session_start();
            $_SESSION['flash_message'] = $message;
            $_SESSION['flash_type'] = $type;
        }
    }
    
    // Redirect back to product list
    header('Location: index.php' . ($redirect_query ? '?' . $redirect_query : ''));
    exit;
}

// Set page title
$page_title = 'Products Management';

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

// Get filter parameters (excluding delete and id)
$search = $_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_item = isset($_GET['stock_item']) && $_GET['stock_item'] !== '' ? (int)$_GET['stock_item'] : null;
$status = $_GET['status'] ?? '';

// Build where clause and parameters
$where_conditions = ["1=1"];
$params = [];

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

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

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

if ($stock_item !== null) {
    $where_conditions[] = "p.stock_item = ?";
    $params[] = $stock_item;
}

if ($status === 'active') {
    $where_conditions[] = "p.is_active = 1";
} elseif ($status === 'inactive') {
    $where_conditions[] = "p.is_active = 0";
}

$where_clause = implode(" AND ", $where_conditions);

// Get products with details
$products = [];
try {
    $sql = "
        SELECT 
            p.*,
            c.category_name,
            o.outlet_name,
            (SELECT COUNT(*) FROM pos_sale_items WHERE product_id = p.product_id) as sales_count,
            CASE 
                WHEN p.stock_item = 1 AND p.current_stock <= p.min_stock THEN 'low'
                WHEN p.stock_item = 1 AND p.current_stock <= 0 THEN 'out'
                ELSE 'normal'
            END as stock_status
        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_clause
        ORDER BY c.category_name, p.product_name";
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $products = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Error fetching products: " . $e->getMessage());
    $products = [];
}

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

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

// Display flash messages from session if function doesn't exist
if (!function_exists('display_flash_messages')) {
    session_start();
    if (isset($_SESSION['flash_message'])) {
        $flash_type = $_SESSION['flash_type'] ?? 'info';
        $flash_message = $_SESSION['flash_message'];
        ?>
        <div class="alert alert-<?php echo $flash_type; ?> alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($flash_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php
        unset($_SESSION['flash_message']);
        unset($_SESSION['flash_type']);
    }
}

// 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>Products Management</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; }
            .mr-1 { margin-right: 0.25rem; }
            .mr-2 { margin-right: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
            .text-right { text-align: right; }
            .table-warning { background-color: #fff3cd; }
            .table-danger { background-color: #f8d7da; }
            .badge.bg-success { background-color: #28a745; color: #fff; }
            .badge.bg-warning { background-color: #ffc107; color: #000; }
            .badge.bg-danger { background-color: #dc3545; color: #fff; }
            .badge.bg-info { background-color: #17a2b8; color: #fff; }
            .badge.bg-secondary { background-color: #6c757d; color: #fff; }
            /* Modal styles */
            .modal-content { border-radius: 0.5rem; }
            .modal-header.bg-danger { background-color: #dc3545 !important; }
            .modal-header.bg-warning { background-color: #ffc107 !important; }
            .btn-close-white { filter: invert(1) grayscale(100%) brightness(200%); }
            .btn-delete { transition: all 0.3s; }
            .btn-delete:hover { transform: scale(1.05); }
            .btn-group .btn { margin: 0 2px; }
        </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="#">Products Management</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">Products Management</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/pos/dashboard.php">POS</a></li>
                    <li class="breadcrumb-item active">Products</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <div id="flash-messages">
            <?php 
            if (function_exists('display_flash_messages')) {
                display_flash_messages();
            }
            ?>
        </div>

        <!-- Filters -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-filter mr-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 name, code, barcode..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-control" 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 htmlspecialchars($cat['category_name'] ?? 'Unknown'); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-control" 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 htmlspecialchars($outlet['outlet_name'] ?? 'Unknown'); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-control" name="stock_item">
                            <option value="">All Types</option>
                            <option value="1" <?php echo $stock_item === 1 ? 'selected' : ''; ?>>Stock Items</option>
                            <option value="0" <?php echo $stock_item === 0 ? 'selected' : ''; ?>>Non-Stock Items</option>
                        </select>
                    </div>
                    
                    <div class="col-md-1">
                        <select class="form-control" name="status">
                            <option value="">All</option>
                            <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo $status == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search mr-1"></i> Apply
                        </button>
                        <a href="?" class="btn btn-secondary">
                            <i class="fas fa-times mr-1"></i> Clear
                        </a>
                    </div>
                    
                    <?php if (function_exists('has_permission') && has_permission('pos.products.manage') || true): ?>
                        <div class="col-md-12 text-right">
                            <a href="create.php" class="btn btn-success">
                                <i class="fas fa-plus"></i> New Product
                            </a>
                        </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <!-- Products Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-box mr-1"></i>
                    Products (<?php echo count($products); ?>)
                </h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-sm btn-primary" onclick="exportProducts()">
                        <i class="fas fa-download"></i> Export
                    </button>
                </div>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($products)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-box-open fa-4x mb-3"></i>
                        <h5>No products found</h5>
                        <p>Create your first product</p>
                        <?php if (function_exists('has_permission') && has_permission('pos.products.manage') || true): ?>
                            <a href="create.php" class="btn btn-primary">
                                <i class="fas fa-plus mr-1"></i> New Product
                            </a>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Code</th>
                                    <th>Name</th>
                                    <th>Category</th>
                                    <th>Outlet</th>
                                    <th>Price</th>
                                    <th class="text-center">Stock</th>
                                    <th>Status</th>
                                    <th>Sales</th>
                                    <th width="160">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($products as $product): ?>
                                <tr class="<?php 
                                    echo ($product['stock_status'] ?? '') == 'low' ? 'table-warning' : '';
                                    echo ($product['stock_status'] ?? '') == 'out' ? 'table-danger' : '';
                                ?>">
                                    <td>
                                        <strong><?php echo htmlspecialchars($product['product_code'] ?? ''); ?></strong>
                                        <?php if (!empty($product['barcode'])): ?>
                                            <br>
                                            <small class="text-muted"><?php echo htmlspecialchars($product['barcode']); ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="view.php?id=<?php echo $product['product_id'] ?? 0; ?>">
                                            <?php echo htmlspecialchars($product['product_name'] ?? ''); ?>
                                        </a>
                                    </td>
                                    <td><?php echo htmlspecialchars($product['category_name'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars($product['outlet_name'] ?? 'All'); ?></td>
                                    <td>
                                        <strong><?php echo function_exists('format_currency') ? format_currency($product['unit_price'] ?? 0) : 'RWF ' . number_format($product['unit_price'] ?? 0); ?></strong>
                                        <?php if (!empty($product['cost_price'])): ?>
                                            <br>
                                            <small class="text-muted">Cost: <?php echo function_exists('format_currency') ? format_currency($product['cost_price']) : 'RWF ' . number_format($product['cost_price']); ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php if (!empty($product['stock_item'])): ?>
                                            <span class="badge bg-<?php 
                                                echo ($product['stock_status'] ?? '') == 'normal' ? 'success' : 
                                                    (($product['stock_status'] ?? '') == 'low' ? 'warning' : 'danger');
                                            ?>">
                                                <?php echo $product['current_stock'] ?? 0; ?> / <?php echo $product['min_stock'] ?? 0; ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">N/A</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($product['is_active'])): ?>
                                            <span class="badge bg-success">Active</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger">Inactive</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-info"><?php echo $product['sales_count'] ?? 0; ?></span>
                                    </td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <a href="view.php?id=<?php echo $product['product_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-info" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            
                                            <?php if (function_exists('has_permission') && has_permission('pos.products.manage') || true): ?>
                                                <a href="edit.php?id=<?php echo $product['product_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-warning" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                
                                                <?php if (!empty($product['barcode'])): ?>
                                                    <a href="barcode.php?id=<?php echo $product['product_id'] ?? 0; ?>" 
                                                       class="btn btn-sm btn-secondary" title="Print Barcode" target="_blank">
                                                        <i class="fas fa-barcode"></i>
                                                    </a>
                                                <?php endif; ?>
                                                
                                                <!-- Delete Button with Confirmation Modal Trigger -->
                                                <button type="button" 
                                                        class="btn btn-sm btn-danger btn-delete" 
                                                        title="Delete"
                                                        onclick="confirmDelete(<?php echo $product['product_id'] ?? 0; ?>, '<?php echo htmlspecialchars(addslashes($product['product_name'] ?? ''), ENT_QUOTES); ?>', <?php echo $product['sales_count'] ?? 0; ?>)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteModalLabel">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Confirm Delete
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p id="deleteMessage" class="fs-5 mb-3"></p>
                <div id="salesWarning" class="alert alert-warning d-none">
                    <i class="fas fa-info-circle me-2"></i>
                    <span id="salesWarningText"></span>
                </div>
                <p class="text-muted small mt-3">
                    <i class="fas fa-question-circle me-1"></i>
                    This action cannot be undone.
                </p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i> Cancel
                </button>
                <a href="#" id="confirmDeleteBtn" class="btn btn-danger">
                    <i class="fas fa-trash me-1"></i> Delete
                </a>
            </div>
        </div>
    </div>
</div>

<script>
// Export function
function exportProducts() {
    window.location.href = 'export.php?' + window.location.search.substring(1);
}

// Delete confirmation function
function confirmDelete(productId, productName, salesCount) {
    // Set up the modal
    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    const messageEl = document.getElementById('deleteMessage');
    const salesWarningEl = document.getElementById('salesWarning');
    const salesWarningTextEl = document.getElementById('salesWarningText');
    const confirmBtn = document.getElementById('confirmDeleteBtn');
    const modalHeader = document.querySelector('#deleteModal .modal-header');
    
    // Build the message
    let message = `Are you sure you want to delete <strong>${productName}</strong>?`;
    messageEl.innerHTML = message;
    
    // Check if product has sales
    if (salesCount > 0) {
        salesWarningEl.classList.remove('d-none');
        salesWarningTextEl.textContent = `This product has ${salesCount} sale(s). It will be deactivated instead of permanently deleted.`;
        confirmBtn.textContent = ' Deactivate';
        confirmBtn.innerHTML = '<i class="fas fa-ban me-1"></i> Deactivate';
        confirmBtn.classList.remove('btn-danger');
        confirmBtn.classList.add('btn-warning');
        modalHeader.classList.remove('bg-danger');
        modalHeader.classList.add('bg-warning');
    } else {
        salesWarningEl.classList.add('d-none');
        confirmBtn.textContent = ' Delete';
        confirmBtn.innerHTML = '<i class="fas fa-trash me-1"></i> Delete';
        confirmBtn.classList.remove('btn-warning');
        confirmBtn.classList.add('btn-danger');
        modalHeader.classList.remove('bg-warning');
        modalHeader.classList.add('bg-danger');
    }
    
    // Set the delete link with current filters preserved
    const currentUrl = new URL(window.location.href);
    // Remove pagination if exists
    currentUrl.searchParams.delete('page');
    currentUrl.searchParams.set('delete', '1');
    currentUrl.searchParams.set('id', productId);
    confirmBtn.href = currentUrl.toString();
    
    // Show the modal
    modal.show();
}

// Add keyboard shortcut for delete (Shift + D)
document.addEventListener('keydown', function(e) {
    if (e.shiftKey && (e.key === 'D' || e.key === 'd')) {
        // Find the first delete button and trigger it
        const firstDeleteBtn = document.querySelector('.btn-delete');
        if (firstDeleteBtn) {
            firstDeleteBtn.click();
        }
    }
});

// Initialize tooltips
document.addEventListener('DOMContentLoaded', function() {
    if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
        tooltipTriggerList.map(function(tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
});
</script>

<?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>';
}
?>