<?php
/**
 * Product Catalog Management
 * XChange 2025 Registration System
 */

require_once 'auth_rbac.php';
require_once '../db_config.php';
require_once 'product_helper.php';
require_once 'ProductLogger.php';

// Get database connection
$conn = getDBConnection();

// Check authentication and permissions
$auth = new AdminAuth($conn);
$auth->requirePermission('registrations');

$productManager = new ProductManager($conn);
$currentPage = 'product-catalog';

// Initialize product logger
$productLogger = new ProductLogger($conn, $auth->getCurrentUser());

// Get category filter from URL
$selectedCategory = isset($_GET['category']) ? intval($_GET['category']) : null;

// Helper function to build redirect URL with category preservation
function buildRedirectUrl($baseUrl = 'product-catalog.php', $category = null) {
    if ($category !== null) {
        return $baseUrl . '?category=' . $category;
    }
    return $baseUrl;
}

// Handle actions
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$auth->hasPermission('payments')) {
        header('Location: access_denied.php');
        exit;
    }
    
    if (isset($_POST['action'])) {
        try {
            switch ($_POST['action']) {
                case 'create_product':
                    $productData = [
                        'category_id' => $_POST['category_id'] ?: null,
                        'product_code' => trim($_POST['product_code']),
                        'name' => trim($_POST['name']),
                        'description' => trim($_POST['description']),
                        'base_price' => floatval($_POST['base_price']),
                        'total_stock' => $_POST['total_stock'] ? intval($_POST['total_stock']) : null,
                        'max_per_registration' => intval($_POST['max_per_registration']) ?: 1,
                        'sale_start_date' => !empty($_POST['sale_start_date']) ? $_POST['sale_start_date'] : null,
                        'sale_end_date' => !empty($_POST['sale_end_date']) ? $_POST['sale_end_date'] : null,
                        'is_active' => isset($_POST['is_active']) ? 1 : 0,
                        'show_in_frontend' => isset($_POST['show_in_frontend']) ? 1 : 0,
                        'display_order' => intval($_POST['display_order']) ?: 0
                    ];
                    
                    // Check for duplicate product code
                    $checkSql = "SELECT COUNT(*) FROM products WHERE product_code = ?";
                    $checkStmt = $conn->prepare($checkSql);
                    $checkStmt->execute([$productData['product_code']]);
                    $existingCount = $checkStmt->fetchColumn();
                    
                    if ($existingCount > 0) {
                        throw new Exception("Product code '{$productData['product_code']}' already exists. Please use a unique product code.");
                    }
                    
                    $productId = createProduct($productData);
                    
                    // Handle attached products
                    if (isset($_POST['attached_products']) && !empty($_POST['attached_products'])) {
                        $attachedProducts = json_decode($_POST['attached_products'], true);
                        if ($attachedProducts) {
                            saveAttachedProducts($productId, $attachedProducts);
                        }
                    }
                    
                    $message = "Product created successfully.";
                    $messageType = "success";
                    
                    // Log product creation
                    $productLogger->logProductCreate($productId, $productData);
                    $auth->logActivity('create_product', "Created product: {$productData['name']} ({$productData['product_code']})");
                    
                    // Redirect to prevent form resubmission
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $messageType;
                    header('Location: ' . buildRedirectUrl('product-catalog.php', $selectedCategory));
                    exit;
                    break;
                    
                case 'update_product':
                    $productId = intval($_POST['product_id']);
                    $productData = [
                        'product_code' => trim($_POST['product_code']),
                        'category_id' => $_POST['category_id'] ?: null,
                        'name' => trim($_POST['name']),
                        'description' => trim($_POST['description']),
                        'base_price' => floatval($_POST['base_price']),
                        'total_stock' => $_POST['total_stock'] ? intval($_POST['total_stock']) : null,
                        'max_per_registration' => intval($_POST['max_per_registration']) ?: 1,
                        'sale_start_date' => !empty($_POST['sale_start_date']) ? $_POST['sale_start_date'] : null,
                        'sale_end_date' => !empty($_POST['sale_end_date']) ? $_POST['sale_end_date'] : null,
                        'is_active' => isset($_POST['is_active']) ? 1 : 0,
                        'show_in_frontend' => isset($_POST['show_in_frontend']) ? 1 : 0,
                        'display_order' => intval($_POST['display_order']) ?: 0
                    ];
                    
                    // Check for duplicate product code (excluding current product)
                    $checkSql = "SELECT COUNT(*) FROM products WHERE product_code = ? AND id != ?";
                    $checkStmt = $conn->prepare($checkSql);
                    $checkStmt->execute([$productData['product_code'], $productId]);
                    $existingCount = $checkStmt->fetchColumn();
                    
                    if ($existingCount > 0) {
                        throw new Exception("Product code '{$productData['product_code']}' already exists. Please use a unique product code.");
                    }
                    
                    // Get old product data for logging
                    $oldProduct = $productManager->getProduct($productId);
                    
                    updateProduct($productId, $productData);
                    
                    // Handle attached products
                    if (isset($_POST['attached_products'])) {
                        $attachedProducts = json_decode($_POST['attached_products'], true);
                        saveAttachedProducts($productId, $attachedProducts ?: []);
                    }
                    
                    $message = "Product updated successfully.";
                    $messageType = "success";
                    
                    // Log product update
                    $productLogger->logProductUpdate($productId, $oldProduct, $productData);
                    $auth->logActivity('update_product', "Updated product ID: {$productId}");
                    
                    // Redirect to prevent form resubmission
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $messageType;
                    header('Location: ' . buildRedirectUrl('product-catalog.php', $selectedCategory));
                    exit;
                    break;
                    
                case 'toggle_status':
                    $productId = intval($_POST['product_id']);
                    $newStatus = intval($_POST['is_active']);
                    
                    // Get product data for logging
                    $product = $productManager->getProduct($productId);
                    $oldStatus = $product['is_active'];
                    
                    $sql = "UPDATE products SET is_active = ?, updated_at = NOW() WHERE id = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$newStatus, $productId]);
                    
                    $statusText = $newStatus ? 'activated' : 'deactivated';
                    $message = "Product {$statusText} successfully.";
                    $messageType = "success";
                    
                    // Log status change
                    $productLogger->logProductStatusChange($productId, $product['name'], $oldStatus, $newStatus);
                    
                    $auth->logActivity('toggle_product_status', "Product ID {$productId} {$statusText}");
                    
                    // Redirect to prevent form resubmission
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $messageType;
                    header('Location: ' . buildRedirectUrl('product-catalog.php', $selectedCategory));
                    exit;
                    break;
                    
                case 'delete_product':
                    $productId = intval($_POST['product_id']);
                    $deleteConfirmation = trim($_POST['delete_confirmation'] ?? '');
                    
                    // Validate confirmation input
                    if (strtoupper($deleteConfirmation) !== 'DELETE') {
                        $message = "Invalid confirmation. Please type 'DELETE' to confirm deletion.";
                        $messageType = "error";
                        break;
                    }
                    
                    // Get product details for validation and logging
                    $sql = "SELECT name, product_code, is_active FROM products WHERE id = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$productId]);
                    $product = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($product) {
                        // Check if product is active - only inactive products can be deleted
                        if ($product['is_active'] == 1) {
                            $message = "Cannot delete active product '{$product['name']}'. Please deactivate it first.";
                            $messageType = "error";
                            break;
                        }
                        // Check if product has any purchases
                        $sql = "SELECT COUNT(*) FROM registration_products WHERE product_id = ?";
                        $stmt = $conn->prepare($sql);
                        $stmt->execute([$productId]);
                        $purchaseCount = $stmt->fetchColumn();
                        
                        if ($purchaseCount > 0) {
                            $message = "Cannot delete product '{$product['name']}' because it has {$purchaseCount} purchase record(s). Deactivate it instead.";
                            $messageType = "error";
                        } else {
                            // Begin transaction for safe deletion
                            $conn->beginTransaction();
                            
                            try {
                                // Delete pricing tiers first
                                $sql = "DELETE FROM product_pricing WHERE product_id = ?";
                                $stmt = $conn->prepare($sql);
                                $stmt->execute([$productId]);
                                
                                // Delete stock movements
                                $sql = "DELETE FROM product_stock_movements WHERE product_id = ?";
                                $stmt = $conn->prepare($sql);
                                $stmt->execute([$productId]);
                                
                                // Delete the product
                                $sql = "DELETE FROM products WHERE id = ?";
                                $stmt = $conn->prepare($sql);
                                $stmt->execute([$productId]);
                                
                                $conn->commit();
                                
                                $message = "Product '{$product['name']}' deleted successfully.";
                                $messageType = "success";
                                
                                // Log product deletion
                                $productLogger->logProductDelete($productId, $product);
                                $auth->logActivity('delete_product', "Deleted product: {$product['name']} ({$product['product_code']})");
                            } catch (Exception $e) {
                                $conn->rollback();
                                $message = "Error deleting product: " . $e->getMessage();
                                $messageType = "error";
                            }
                        }
                    } else {
                        $message = "Product not found.";
                        $messageType = "error";
                    }
                    
                    // Redirect to prevent form resubmission
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $messageType;
                    header('Location: ' . buildRedirectUrl('product-catalog.php', $selectedCategory));
                    exit;
                    break;
                    
                case 'duplicate_product':
                    $originalId = intval($_POST['product_id']);
                    
                    // Get original product data
                    $sql = "SELECT * FROM products WHERE id = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$originalId]);
                    $original = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($original) {
						try {
							// Generate unique product code
							$baseCode = $original['product_code'];
							$counter = 1;
							$newCode = $baseCode . '_COPY';
							
							// Check if code exists and increment
							while (true) {
								$checkSql = "SELECT id FROM products WHERE product_code = ?";
								$checkStmt = $conn->prepare($checkSql);
								$checkStmt->execute([$newCode]);
								
								if (!$checkStmt->fetch()) {
									break;
								}
								
								$counter++;
								$newCode = $baseCode . '_COPY' . $counter;
							}
							
							// Begin transaction for duplicating product and pricing tiers
							$conn->beginTransaction();
							
							// Create duplicate product
							$duplicateData = [
								'category_id' => $original['category_id'],
								'product_code' => $newCode,
								'name' => $original['name'] . ' (Copy)',
								'description' => $original['description'],
								'base_price' => $original['base_price'],
								'total_stock' => $original['total_stock'],
								'max_per_registration' => $original['max_per_registration'],
								'sale_start_date' => $original['sale_start_date'] ?? null,
								'sale_end_date' => $original['sale_end_date'] ?? null,
								'is_active' => 0,
								'show_in_frontend' => 0,
								'display_order' => $original['display_order']
							];
							
							$newId = createProduct($duplicateData);
							
							// Copy pricing tiers from original product to the new product
							$tierSql = "SELECT pricing_tier, price, valid_from, valid_until, is_active FROM product_pricing WHERE product_id = ?";
							$tierStmt = $conn->prepare($tierSql);
							$tierStmt->execute([$originalId]);
							$tiers = $tierStmt->fetchAll(PDO::FETCH_ASSOC);
							
							if (!empty($tiers)) {
								$insertTierSql = "INSERT INTO product_pricing (product_id, pricing_tier, price, valid_from, valid_until, is_active, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())";
								$insertTierStmt = $conn->prepare($insertTierSql);
								foreach ($tiers as $tier) {
									$insertTierStmt->execute([
										$newId,
										$tier['pricing_tier'],
										$tier['price'],
										$tier['valid_from'],
										$tier['valid_until'],
										$tier['is_active']
									]);
								}
							}
							
							$conn->commit();
							
							$message = "Product duplicated successfully. New product code: {$newCode}";
							$messageType = "success";
							$auth->logActivity('duplicate_product', "Duplicated product ID {$originalId} to new ID {$newId}");
							
							// Redirect to prevent form resubmission
							$_SESSION['flash_message'] = $message;
							$_SESSION['flash_type'] = $messageType;
							header('Location: ' . buildRedirectUrl('product-catalog.php', $selectedCategory));
							exit;
						} catch (Exception $e) {
							// Rollback on any error
							if ($conn->inTransaction()) {
								$conn->rollBack();
							}
							$message = "Error duplicating product: " . $e->getMessage();
							$messageType = "error";
							$_SESSION['flash_message'] = $message;
							$_SESSION['flash_type'] = $messageType;
							header('Location: ' . buildRedirectUrl('product-catalog.php', $selectedCategory));
							exit;
						}
                    } else {
                        $message = "Error: Original product not found.";
                        $messageType = "error";
                        
                        // Redirect to prevent form resubmission
                        $_SESSION['flash_message'] = $message;
                        $_SESSION['flash_type'] = $messageType;
                        header('Location: ' . buildRedirectUrl('product-catalog.php', $selectedCategory));
                        exit;
                    }
                    break;
                    
                case 'save_pricing':
                    $productId = intval($_POST['product_id']);
                    $basePrice = floatval($_POST['base_price']);
                    $tiers = json_decode($_POST['pricing_tiers'], true);
                    
                    // Update base price
                    $updateSql = "UPDATE products SET base_price = ?, updated_at = NOW() WHERE id = ?";
                    $updateStmt = $conn->prepare($updateSql);
                    $updateStmt->execute([$basePrice, $productId]);
                    
                    // Delete existing pricing tiers
                    $deleteSql = "DELETE FROM product_pricing WHERE product_id = ?";
                    $deleteStmt = $conn->prepare($deleteSql);
                    $deleteStmt->execute([$productId]);
                    
                    // Insert new pricing tiers
                    if (!empty($tiers)) {
                        $insertSql = "INSERT INTO product_pricing (product_id, pricing_tier, price, valid_from, valid_until, is_active, created_at) VALUES (?, ?, ?, ?, ?, 1, NOW())";
                        $insertStmt = $conn->prepare($insertSql);
                        
                        foreach ($tiers as $tier) {
                            $validFrom = !empty($tier['valid_from']) ? $tier['valid_from'] : null;
                            $validUntil = !empty($tier['valid_until']) ? $tier['valid_until'] : null;
                            
                            $insertStmt->execute([
                                $productId,
                                $tier['name'],
                                floatval($tier['price']),
                                $validFrom,
                                $validUntil
                            ]);
                        }
                    }
                    
                    $message = "Pricing tiers saved successfully.";
                    $messageType = "success";
                    
                    // Get product name for logging
                    $product = $productManager->getProduct($productId);
                    $productLogger->logPricingUpdate($productId, $product['name'], $pricingTiers);
                    $auth->logActivity('save_pricing', "Updated pricing for product ID {$productId}");
                    
                    // Redirect to prevent form resubmission
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $messageType;
                    header('Location: ' . buildRedirectUrl('product-catalog.php', $selectedCategory));
                    exit;
                    break;
                    
                case 'create_category':
                    $categoryData = [
                        'name' => trim($_POST['category_name']),
                        'description' => trim($_POST['category_description']),
                        'display_order' => intval($_POST['display_order']) ?: 0
                    ];
                    
                    $newCategoryId = $productManager->createCategory($categoryData);
                    $message = "Category '{$categoryData['name']}' created successfully.";
                    $messageType = "success";
                    
                    // Log category creation
                    $productLogger->logCategoryCreate($newCategoryId, $categoryData);
                    $auth->logActivity('create_category', "Created category: {$categoryData['name']}");
                    
                    // Redirect to prevent form resubmission
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $messageType;
                    header('Location: product-catalog.php');
                    exit;
                    break;
                    
                case 'update_category':
                    $categoryId = intval($_POST['category_id']);
                    $categoryData = [
                        'name' => trim($_POST['category_name']),
                        'description' => trim($_POST['category_description']),
                        'display_order' => intval($_POST['display_order']) ?: 0,
                        'is_active' => isset($_POST['is_active']) ? 1 : 0
                    ];
                    
                    // Get old category data for logging
                    $oldCategory = $productManager->getCategoryById($categoryId);
                    
                    $productManager->updateCategory($categoryId, $categoryData);
                    $message = "Category updated successfully.";
                    $messageType = "success";
                    
                    // Log category update
                    $productLogger->logCategoryUpdate($categoryId, $oldCategory, $categoryData);
                    $auth->logActivity('update_category', "Updated category ID: {$categoryId}");
                    
                    // Redirect to prevent form resubmission
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $messageType;
                    header('Location: product-catalog.php');
                    exit;
                    break;
                    
                case 'delete_category':
                    $categoryId = intval($_POST['category_id']);
                    
                    try {
                        $category = $productManager->getCategoryById($categoryId);
                        $productManager->deleteCategory($categoryId);
                        $message = "Category '{$category['name']}' deleted successfully.";
                        $messageType = "success";
                        
                        // Log category deletion
                        $productLogger->logCategoryDelete($categoryId, $category);
                        $auth->logActivity('delete_category', "Deleted category: {$category['name']}");
                        
                        // Redirect to prevent form resubmission
                        $_SESSION['flash_message'] = $message;
                        $_SESSION['flash_type'] = $messageType;
                        header('Location: product-catalog.php');
                        exit;
                    } catch (Exception $e) {
                        $message = $e->getMessage();
                        $messageType = "error";
                        
                        // Redirect to prevent form resubmission even on error
                        $_SESSION['flash_message'] = $message;
                        $_SESSION['flash_type'] = $messageType;
                        header('Location: product-catalog.php');
                        exit;
                    }
                    break;
            }
        } catch (Exception $e) {
            $message = "Error: " . $e->getMessage();
            $messageType = "error";
        }
    }
}

// Handle flash messages from redirects
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $messageType = $_SESSION['flash_type'];
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
}

// Get data
$categories = $productManager->getProductCategories();
$allCategories = $productManager->getProductCategories(true); // Include inactive for management

// Apply category filter if selected
$filters = [];
if ($selectedCategory) {
    $filters['category_id'] = $selectedCategory;
}
$products = $productManager->getProducts($filters);

// Get pricing tiers for all products
$pricingData = [];
$attachedProductsData = [];
if (!empty($products)) {
    $productIds = array_column($products, 'id');
    $placeholders = str_repeat('?,', count($productIds) - 1) . '?';
    
    // Get pricing data
    $pricingSql = "SELECT product_id, pricing_tier, price FROM product_pricing WHERE product_id IN ($placeholders) AND is_active = 1 ORDER BY product_id, pricing_tier";
    $pricingStmt = $conn->prepare($pricingSql);
    $pricingStmt->execute($productIds);
    $pricingResults = $pricingStmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($pricingResults as $pricing) {
        $pricingData[$pricing['product_id']][] = $pricing;
    }
    
    // Get attached products data
    $attachedSql = "SELECT pa.parent_product_id, pa.quantity, p.name as product_name, p.product_code
                    FROM product_attachments pa
                    JOIN products p ON pa.attached_product_id = p.id
                    WHERE pa.parent_product_id IN ($placeholders) AND pa.is_active = 1
                    ORDER BY pa.parent_product_id, pa.display_order, p.name";
    $attachedStmt = $conn->prepare($attachedSql);
    $attachedStmt->execute($productIds);
    $attachedResults = $attachedStmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($attachedResults as $attached) {
        $attachedProductsData[$attached['parent_product_id']][] = $attached;
    }
}

// Helper functions
function createProduct($data) {
    global $conn;
    
    $sql = "INSERT INTO products (category_id, product_code, name, description, base_price, 
                                 total_stock, max_per_registration, sale_start_date, sale_end_date,
                                 is_active, show_in_frontend, display_order)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute([
        $data['category_id'], $data['product_code'], $data['name'], $data['description'],
        $data['base_price'], $data['total_stock'], $data['max_per_registration'],
        $data['sale_start_date'], $data['sale_end_date'], $data['is_active'], $data['show_in_frontend'], $data['display_order']
    ]);
    
    return $conn->lastInsertId();
}

function updateProduct($id, $data) {
    global $conn;
    
    $sql = "UPDATE products SET category_id = ?, product_code = ?, name = ?, description = ?, base_price = ?,
                               total_stock = ?, max_per_registration = ?, sale_start_date = ?,
                               sale_end_date = ?, is_active = ?, show_in_frontend = ?, display_order = ?, updated_at = NOW()
            WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute([
        $data['category_id'], $data['product_code'], $data['name'], $data['description'], $data['base_price'],
        $data['total_stock'], $data['max_per_registration'], $data['sale_start_date'],
        $data['sale_end_date'], $data['is_active'], $data['show_in_frontend'], $data['display_order'], $id
    ]);
}


function getDefaultTierName($productId, $basePrice) {
    global $conn;
    
    // Find the default tier (one with base price and no date restrictions)
    $sql = "SELECT pricing_tier FROM product_pricing 
            WHERE product_id = ? AND price = ? AND valid_from IS NULL AND valid_until IS NULL 
            ORDER BY created_at ASC LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$productId, $basePrice]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    return $result ? $result['pricing_tier'] : '';
}

function getProductsWithDetails($categoryFilter = '') {
    global $conn;
    
    $sql = "SELECT p.*, pc.name as category_name,
                   CASE 
                       WHEN p.total_stock IS NULL THEN 'unlimited'
                       WHEN p.available_stock > (p.total_stock * 0.5) THEN 'high'
                       WHEN p.available_stock > 0 THEN 'low'
                       ELSE 'out'
                   END as stock_level
            FROM products p
            LEFT JOIN product_categories pc ON p.category_id = pc.id";
    
    $params = [];
    
    if ($categoryFilter) {
        $sql .= " WHERE p.category_id = ?";
        $params[] = $categoryFilter;
    }
    
    $sql .= " ORDER BY pc.display_order, p.display_order, p.name";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function saveAttachedProducts($parentProductId, $attachedProducts) {
    global $conn;
    
    // Begin transaction
    $conn->beginTransaction();
    
    try {
        // Delete existing attachments
        $deleteSql = "DELETE FROM product_attachments WHERE parent_product_id = ?";
        $deleteStmt = $conn->prepare($deleteSql);
        $deleteStmt->execute([$parentProductId]);
        
        // Insert new attachments
        if (!empty($attachedProducts)) {
            $insertSql = "INSERT INTO product_attachments (parent_product_id, attached_product_id, quantity, display_order, notes, created_at) VALUES (?, ?, ?, ?, ?, NOW())";
            $insertStmt = $conn->prepare($insertSql);
            
            foreach ($attachedProducts as $index => $attachment) {
                $insertStmt->execute([
                    $parentProductId,
                    intval($attachment['product_id']),
                    intval($attachment['quantity']),
                    $index,
                    $attachment['notes'] ?? null
                ]);
            }
        }
        
        $conn->commit();
        return true;
    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }
}

function getAttachedProducts($parentProductId) {
    global $conn;
    
    $sql = "SELECT pa.*, p.name as product_name, p.product_code, p.base_price, pc.name as category_name
            FROM product_attachments pa
            JOIN products p ON pa.attached_product_id = p.id
            LEFT JOIN product_categories pc ON p.category_id = pc.id
            WHERE pa.parent_product_id = ? AND pa.is_active = 1
            ORDER BY pa.display_order, p.name";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute([$parentProductId]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Catalog - XChange 2025 Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <link rel="stylesheet" href="product-catalog.css">
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>
    
    <div class="admin-content">
        <div class="page-header">
            <h1>Product Catalog Management</h1>
            <p>Manage products, categories, and pricing tiers</p>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <!-- Category Management Header -->
        <div class="category-header">
            <div class="category-tabs">
                <button class="category-tab <?php echo empty($selectedCategory) ? 'active' : ''; ?>" 
                        onclick="filterByCategory('')">
                    <svg class="category-tab-icon" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/>
                    </svg>
                    All Products
                </button>
                <?php foreach ($categories as $category): ?>
                    <button class="category-tab <?php echo $selectedCategory == $category['id'] ? 'active' : ''; ?>" 
                            onclick="filterByCategory(<?php echo $category['id']; ?>)">
                        <?php
                        // Set appropriate icon based on category name
                        $icon = '';
                        $categoryName = strtolower($category['name']);
                        if (strpos($categoryName, 'delegate') !== false) {
                            $icon = '<svg class="category-tab-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>';
                        } elseif (strpos($categoryName, 'presentation') !== false) {
                            $icon = '<svg class="category-tab-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5l-1 1v2h8v-2h-1l-1-1h5c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-1 12H4V5h16v10z"/></svg>';
                        } elseif (strpos($categoryName, 'sponsorship') !== false) {
                            $icon = '<svg class="category-tab-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>';
                        } else {
                            $icon = '<svg class="category-tab-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/></svg>';
                        }
                        echo $icon;
                        ?>
                        <?php echo htmlspecialchars($category['name']); ?>
                    </button>
                <?php endforeach; ?>
                
                <!-- Manage Categories button inside the tabs container -->
                <button class="btn-manage-categories" onclick="openCategoryModal()">
                    <svg class="category-tab-icon" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M19.14,12.94c0.04-0.3,0.06-0.61,0.06-0.94c0-0.32-0.02-0.64-0.07-0.94l2.03-1.58c0.18-0.14,0.23-0.41,0.12-0.61 l-1.92-3.32c-0.12-0.22-0.37-0.29-0.59-0.22l-2.39,0.96c-0.5-0.38-1.03-0.7-1.62-0.94L14.4,2.81c-0.04-0.24-0.24-0.41-0.48-0.41 h-3.84c-0.24,0-0.43,0.17-0.47,0.41L9.25,5.35C8.66,5.59,8.12,5.92,7.63,6.29L5.24,5.33c-0.22-0.08-0.47,0-0.59,0.22L2.74,8.87 C2.62,9.08,2.66,9.34,2.86,9.48l2.03,1.58C4.84,11.36,4.8,11.69,4.8,12s0.02,0.64,0.07,0.94l-2.03,1.58 c-0.18,0.14-0.23,0.41-0.12,0.61l1.92,3.32c0.12,0.22,0.37,0.29,0.59,0.22l2.39-0.96c0.5,0.38,1.03,0.7,1.62,0.94l0.36,2.54 c0.05,0.24,0.24,0.41,0.48,0.41h3.84c0.24,0,0.44-0.17,0.47-0.41l0.36-2.54c0.59-0.24,1.13-0.56,1.62-0.94l2.39,0.96 c0.22,0.08,0.47,0,0.59-0.22l1.92-3.32c0.12-0.22,0.07-0.47-0.12-0.61L19.14,12.94z M12,15.6c-1.98,0-3.6-1.62-3.6-3.6 s1.62-3.6,3.6-3.6s3.6,1.62,3.6,3.6S13.98,15.6,12,15.6z"/>
                    </svg>
                    Manage Categories
                </button>
            </div>
        </div>

        <!-- Products Grid -->
        <?php if (empty($products)): ?>
            <div class="empty-state">
                <div class="empty-state-icon">📦</div>
                <h3>No Products Found</h3>
                <p>Start building your product catalog by creating your first product.</p>
                <button onclick="openProductModal()" class="btn-create-first">Create First Product</button>
            </div>
        <?php else: ?>
            <div class="product-grid">
                <?php foreach ($products as $product): ?>
                    <div class="product-card">
                        <div class="product-header">
                            <div>
                                <h3 class="product-title"><?php echo htmlspecialchars($product['name']); ?></h3>
                                <div class="product-code"><?php echo htmlspecialchars($product['product_code']); ?></div>
                            </div>
                            <div class="product-status">
                                <div class="status-toggle <?php echo $product['is_active'] ? 'active' : ''; ?>" 
                                     onclick="toggleProductStatus(<?php echo $product['id']; ?>, <?php echo $product['is_active'] ? 0 : 1; ?>)"
                                     title="<?php echo $product['is_active'] ? 'Active' : 'Inactive'; ?>">
                                </div>
                                <div class="frontend-visibility-indicator <?php echo $product['show_in_frontend'] ? 'visible' : 'hidden'; ?>"
                                     title="<?php echo $product['show_in_frontend'] ? 'Visible in Frontend' : 'Hidden from Frontend'; ?>">
                                    <?php if ($product['show_in_frontend']): ?>
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                            <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                                        </svg>
                                    <?php else: ?>
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                            <path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/>
                                        </svg>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <?php if ($product['description']): ?>
                            <div class="product-description">
                                <?php echo $product['description']; ?>
                            </div>
                        <?php endif; ?>
                        
                        <div class="product-details">
                            <div class="detail-item">
                                <div class="detail-label">Base Price</div>
                                <div class="detail-value">$<?php echo number_format($product['base_price'], 2); ?></div>
                            </div>
                            <?php if (isset($pricingData[$product['id']]) && !empty($pricingData[$product['id']])): ?>
                                <div class="detail-item pricing-tiers-preview">
                                    <div class="detail-label">Pricing Tiers</div>
                                    <div class="detail-value">
                                        <?php foreach ($pricingData[$product['id']] as $tier): ?>
                                            <div class="tier-preview">
                                                <span class="tier-name"><?php echo htmlspecialchars($tier['pricing_tier']); ?></span>
                                                <span class="tier-price">$<?php echo number_format($tier['price'], 2); ?></span>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                            <div class="detail-item">
                                <div class="detail-label">Stock</div>
                                <div class="detail-value">
                                    <?php if ($product['total_stock'] == -1): ?>
                                        Unlimited
                                    <?php else: ?>
                                        <?php echo $product['available_stock']; ?> / <?php echo $product['total_stock']; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Max Per Order</div>
                                <div class="detail-value"><?php echo $product['max_per_registration']; ?></div>
                            </div>
                        </div>
                        
                        <?php if (isset($attachedProductsData[$product['id']]) && !empty($attachedProductsData[$product['id']])): ?>
                            <div class="attached-products-preview">
                                <div class="detail-label">Includes</div>
                                <div class="attached-products-list-preview">
                                    <?php foreach ($attachedProductsData[$product['id']] as $attached): ?>
                                        <div class="attached-product-preview">
                                            <span class="attached-product-name"><?php echo htmlspecialchars($attached['product_name']); ?></span>
                                            <span class="attached-product-qty">×<?php echo $attached['quantity']; ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($auth->hasPermission('payments')): ?>
                            <div class="product-actions">
                                <div class="primary-actions">
                                    <button onclick="editProduct(<?php echo htmlspecialchars(json_encode($product)); ?>)" 
                                            class="btn-edit-product">Edit</button>
                                    <button onclick="managePricing(<?php echo $product['id']; ?>)" 
                                            class="btn-pricing">Pricing</button>
                                </div>
                                <button onclick="duplicateProduct(<?php echo $product['id']; ?>)" 
                                        class="btn-duplicate-product" title="Duplicate this product">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                                        <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
                                    </svg>
                                </button>
                                <?php if ($product['is_active'] == 0): ?>
                                    <button onclick="confirmDeleteProduct(<?php echo $product['id']; ?>, '<?php echo htmlspecialchars($product['name'], ENT_QUOTES); ?>')" 
                                            class="btn-delete-product" title="Delete this inactive product">
                                        <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                                            <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                                        </svg>
                                    </button>
                                <?php else: ?>
                                    <button class="btn-delete-product-disabled" title="Deactivate product first to enable deletion" disabled>
                                        <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                                            <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                                        </svg>
                                    </button>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <!-- Add Product Button -->
        <?php if ($auth->hasPermission('payments')): ?>
            <button onclick="openProductModal()" class="add-product-btn">+</button>
        <?php endif; ?>
    </div>

    <!-- Product Modal -->
    <?php if ($auth->hasPermission('payments')): ?>
        <div id="productModal" class="product-modal">
            <div class="product-modal-content">
                <div class="product-modal-header">
                    <h3 id="modalTitle" class="product-modal-title">Add New Product</h3>
                    <button onclick="closeProductModal()" class="modal-close">&times;</button>
                </div>
                <form id="productForm" method="POST" onsubmit="debugFormSubmission(event)">
                    <div class="product-modal-body">
                        <input type="hidden" name="action" id="formAction" value="create_product">
                        <input type="hidden" name="product_id" id="productId">
                        <input type="hidden" name="attached_products" id="attachedProductsData">
                        
                        <div class="form-grid">
                            <div class="form-group">
                                <label class="form-label">Product Code *</label>
                                <input type="text" name="product_code" id="productCode" class="form-input" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Category</label>
                                <select name="category_id" id="productCategoryId" class="form-select">
                                    <option value="">Uncategorized</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?php echo $category['id']; ?>">
                                            <?php echo htmlspecialchars($category['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="form-group form-group-full">
                                <label class="form-label">Product Name *</label>
                                <input type="text" name="name" id="productName" class="form-input" required>
                            </div>
                            <div class="form-group form-group-full">
                                <label class="form-label">Description</label>
                                <div class="editor-toolbar">
                                    <button type="button" class="editor-btn" onclick="formatText('bold')" title="Bold"><b>B</b></button>
                                    <button type="button" class="editor-btn" onclick="formatText('italic')" title="Italic"><i>I</i></button>
                                    <button type="button" class="editor-btn" onclick="formatText('underline')" title="Underline"><u>U</u></button>
                                    <button type="button" class="editor-btn" onclick="formatText('insertUnorderedList')" title="Bullet List">•</button>
                                    <button type="button" class="editor-btn" onclick="formatText('insertOrderedList')" title="Numbered List">1.</button>
                                    <button type="button" class="editor-btn" onclick="formatText('createLink')" title="Link">🔗</button>
                                    <button type="button" class="editor-btn" onclick="toggleHtmlView()" title="Toggle HTML View" id="htmlToggleBtn">&lt;/&gt;</button>
                                </div>
                                <div id="productDescriptionEditor" class="form-editor" contenteditable="true" placeholder="Enter product description..."></div>
                                <textarea name="description" id="productDescription" class="form-textarea" style="display: none;"></textarea>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Base Price *</label>
                                <input type="number" name="base_price" id="basePrice" class="form-input" 
                                       step="0.01" min="0" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Total Stock</label>
                                <input type="number" name="total_stock" id="totalStock" class="form-input" 
                                       min="0" placeholder="Leave empty for unlimited">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Max Per Registration</label>
                                <input type="number" name="max_per_registration" id="maxPerReg" class="form-input" 
                                       min="1" value="1" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Display Order</label>
                                <input type="number" name="display_order" id="displayOrder" class="form-input" 
                                       min="0" value="0">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Sale Start Date</label>
                                <input type="datetime-local" name="sale_start_date" id="saleStartDate" class="form-input">
                                <small class="form-help">Leave empty if product is always available</small>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Sale End Date</label>
                                <input type="datetime-local" name="sale_end_date" id="saleEndDate" class="form-input">
                                <small class="form-help">Leave empty if product never expires</small>
                            </div>
                            <div class="form-group form-group-full">
                                <div class="checkbox-group">
                                    <input type="checkbox" name="is_active" id="isActive">
                                    <label for="isActive" class="form-label">Product is active</label>
                                </div>
                            </div>
                            <div class="form-group form-group-full">
                                <div class="checkbox-group">
                                    <input type="checkbox" name="show_in_frontend" id="showInFrontend">
                                    <label for="showInFrontend" class="form-label">Show in frontend registration</label>
                                    <small class="form-help">Uncheck to hide from customer registration forms while keeping active in backend</small>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Attached Products Section -->
                        <div class="form-section">
                            <div class="form-section-header">
                                <h4>Attached Products</h4>
                                <p class="form-section-description">Configure products that are included with this product (e.g., delegate passes included with sponsor packages)</p>
                            </div>
                            <div class="attached-products-container">
                                <div id="attachedProductsList" class="attached-products-list">
                                    <!-- Attached products will be dynamically added here -->
                                </div>
                                <button type="button" onclick="addAttachedProduct()" class="btn-add-attachment">
                                    + Add Attached Product
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="product-modal-footer">
                        <button type="button" onclick="closeProductModal()" class="btn-cancel">Cancel</button>
                        <button type="submit" class="btn-save">Save Product</button>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>

    <!-- New Pricing Management Modal -->
    <?php if ($auth->hasPermission('payments')): ?>
        <div id="pricingModal" class="new-pricing-modal">
            <div class="new-pricing-modal-backdrop" onclick="closePricingModal()"></div>
            <div class="new-pricing-modal-container">
                <div class="new-pricing-modal-header">
                    <div class="new-pricing-modal-title">
                        <h2>Manage Product Pricing</h2>
                        <p class="new-pricing-modal-subtitle">Set base price and configure pricing tiers</p>
                    </div>
                    <button onclick="closePricingModal()" class="new-pricing-modal-close">
                        ×
                    </button>
                </div>
                
                <div class="new-pricing-modal-content">
                    <input type="hidden" id="pricingProductId">
                    
                    <!-- Product Info Section -->
                    <div class="new-pricing-section">
                        <div class="new-pricing-section-header">
                            <i class="fas fa-box"></i>
                            <span>Product Information</span>
                        </div>
                        <div class="new-pricing-product-info">
                            <div class="new-pricing-product-name" id="pricingProductName">Product Name</div>
                            <div class="new-pricing-base-price-container">
                                <label for="pricingBasePrice">Base Price (RM)</label>
                                <input type="number" id="pricingBasePrice" step="0.01" min="0" placeholder="0.00">
                                <small>Default price when no tiers are active</small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Pricing Tiers Section -->
                    <div class="new-pricing-section">
                        <div class="new-pricing-section-header">
                            <i class="fas fa-layer-group"></i>
                            <span>Pricing Tiers</span>
                            <button type="button" onclick="addNewPricingTier()" class="new-add-tier-btn">
                                <i class="fas fa-plus"></i>
                                Add Tier
                            </button>
                        </div>
                        <div id="newPricingTiers" class="new-pricing-tiers-list">
                            <!-- Tiers will be dynamically added here -->
                        </div>
                        <div class="new-pricing-empty-state" id="emptyTiersState">
                            <i class="fas fa-layer-group"></i>
                            <p>No pricing tiers configured</p>
                            <small>Add tiers to offer different prices based on date ranges</small>
                        </div>
                    </div>
                </div>
                
                <div class="new-pricing-modal-footer">
                    <button type="button" onclick="closePricingModal()" class="new-btn-secondary">
                        Cancel
                    </button>
                    <button type="button" onclick="saveNewPricingTiers()" class="new-btn-primary">
                        <i class="fas fa-save"></i>
                        Save Pricing
                    </button>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="delete-modal">
        <div class="delete-modal-content">
            <div class="delete-modal-header">
                <div class="delete-modal-icon">
                    <svg fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>
                    </svg>
                </div>
                <h3>Confirm Product Deletion</h3>
                <button onclick="closeDeleteModal()" class="modal-close">&times;</button>
            </div>
            <div class="delete-modal-body">
                <div id="deleteMessage" class="delete-message"></div>
                
                <div class="confirmation-section">
                    <label class="form-label">Type <strong>DELETE</strong> to confirm:</label>
                    <input type="text" id="deleteConfirmInput" class="delete-confirm-input" placeholder="Type DELETE here">
                    <div class="form-help">This action cannot be undone</div>
                </div>
            </div>
            <div class="delete-modal-footer">
                <button type="button" onclick="closeDeleteModal()" class="btn-cancel-delete">Cancel</button>
                <button type="button" id="confirmDeleteBtn" onclick="executeDelete()" class="btn-confirm-delete" disabled>Delete Product</button>
            </div>
        </div>
    </div>

    <!-- Category Management Modal -->
    <?php if ($auth->hasPermission('payments')): ?>
        <div id="categoryModal" class="category-modal">
            <div class="category-modal-content">
                <div class="category-modal-header">
                    <h3>Manage Product Categories</h3>
                    <button onclick="closeCategoryModal()" class="modal-close">&times;</button>
                </div>
                <div class="category-modal-body">
                    <div class="category-actions">
                        <button onclick="openCategoryForm()" class="btn-create">+ New Category</button>
                    </div>
                    
                    <div class="categories-list">
                        <?php foreach ($allCategories as $category): ?>
                            <div class="category-item <?php echo $category['is_active'] ? 'active' : 'inactive'; ?>">
                                <div class="category-info">
                                    <h4><?php echo htmlspecialchars($category['name']); ?></h4>
                                    <p><?php echo htmlspecialchars($category['description']); ?></p>
                                    <div class="category-meta">
                                        <span class="display-order">Order: <?php echo $category['display_order']; ?></span>
                                        <span class="product-count">Products: <?php echo $category['product_count']; ?></span>
                                        <span class="status-badge <?php echo $category['is_active'] ? 'active' : 'inactive'; ?>">
                                            <?php echo $category['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="category-actions">
                                    <button onclick="editCategory(<?php echo $category['id']; ?>)" class="btn-edit">Edit</button>
                                    <?php if ($category['product_count'] > 0): ?>
                                        <button class="btn-delete-small disabled" disabled title="Cannot delete category with <?php echo $category['product_count']; ?> product(s)">
                                            Delete
                                        </button>
                                    <?php else: ?>
                                        <button onclick="deleteCategory(<?php echo $category['id']; ?>)" class="btn-delete-small">Delete</button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- Category Form Modal -->
    <?php if ($auth->hasPermission('payments')): ?>
        <div id="categoryFormModal" class="category-form-modal">
            <div class="category-form-content">
                <div class="category-form-header">
                    <h3 id="categoryFormTitle">Create New Category</h3>
                    <button onclick="closeCategoryForm()" class="modal-close">&times;</button>
                </div>
                <form id="categoryForm" method="POST">
                    <input type="hidden" name="action" id="categoryAction" value="create_category">
                    <input type="hidden" name="category_id" id="categoryId">
                    
                    <div class="category-form-body">
                        <div class="form-group">
                            <label class="form-label">Category Name *</label>
                            <input type="text" name="category_name" id="categoryName" class="form-input" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Description</label>
                            <textarea name="category_description" id="categoryDescription" class="form-input" rows="3"></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Display Order</label>
                            <input type="number" name="display_order" id="categoryDisplayOrder" class="form-input" min="0" value="0">
                            <div class="form-help">Lower numbers appear first in the category tabs</div>
                        </div>
                        
                        <div class="form-group" id="activeCheckboxGroup" style="display: none;">
                            <div class="checkbox-group">
                                <input type="checkbox" name="is_active" id="categoryIsActive">
                                <label for="categoryIsActive" class="form-label">Category is active</label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="category-form-footer">
                        <button type="button" onclick="closeCategoryForm()" class="btn-cancel">Cancel</button>
                        <button type="submit" class="btn-save">Save Category</button>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>

    <script>
        let deleteProductId = null;
        let deleteProductName = '';

        // Notification function to show messages on page instead of popups
        function showNotification(message, type = 'success') {
            // Create notification element
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            notification.innerHTML = `
                <div class="notification-content">
                    <span class="notification-message">${message}</span>
                    <button class="notification-close" onclick="this.parentElement.parentElement.remove()">&times;</button>
                </div>
            `;
            
            // Add styles if not already added
            if (!document.getElementById('notification-styles')) {
                const styles = document.createElement('style');
                styles.id = 'notification-styles';
                styles.textContent = `
                    .notification {
                        position: fixed;
                        top: 20px;
                        right: 20px;
                        padding: 15px 20px;
                        border-radius: 5px;
                        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                        z-index: 10000;
                        max-width: 400px;
                        animation: slideIn 0.3s ease-out;
                    }
                    .notification.success {
                        background-color: #d4edda;
                        color: #155724;
                        border: 1px solid #c3e6cb;
                    }
                    .notification.error {
                        background-color: #f8d7da;
                        color: #721c24;
                        border: 1px solid #f5c6cb;
                    }
                    .notification-content {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                    }
                    .notification-close {
                        background: none;
                        border: none;
                        font-size: 18px;
                        cursor: pointer;
                        margin-left: 10px;
                        opacity: 0.7;
                    }
                    .notification-close:hover {
                        opacity: 1;
                    }
                    @keyframes slideIn {
                        from { transform: translateX(100%); opacity: 0; }
                        to { transform: translateX(0); opacity: 1; }
                    }
                `;
                document.head.appendChild(styles);
            }
            
            // Add to page
            document.body.appendChild(notification);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                if (notification.parentElement) {
                    notification.remove();
                }
            }, 5000);
        }

        function filterByCategory(categoryId) {
            // Add loading state to all tabs
            const allTabs = document.querySelectorAll('.category-tab');
            allTabs.forEach(tab => tab.classList.add('loading'));
            
            // Remove active class from all tabs
            allTabs.forEach(tab => tab.classList.remove('active'));
            
            // Add active class to clicked tab
            const clickedTab = event.target.closest('.category-tab');
            if (clickedTab) {
                clickedTab.classList.remove('loading');
                clickedTab.classList.add('active');
            }
            
            // Small delay to show loading state
            setTimeout(() => {
                const url = new URL(window.location);
                if (categoryId) {
                    url.searchParams.set('category', categoryId);
                } else {
                    url.searchParams.delete('category');
                }
                window.location = url;
            }, 150);
        }

        function confirmDeleteProduct(productId, productName) {
            deleteProductId = productId;
            deleteProductName = productName;
            
            document.getElementById('deleteMessage').innerHTML = `
                Are you sure you want to delete "<strong>${productName}</strong>"?<br><br>
                <span style="color: #dc2626; font-weight: 600;">⚠️ This will permanently delete:</span><br>
                • The product and all its data<br>
                • All pricing tiers for this product<br>
                • All purchase history records<br><br>
                <span style="color: #dc2626;">This action cannot be undone!</span>
            `;
            
            // Reset confirmation input
            const confirmInput = document.getElementById('deleteConfirmInput');
            const confirmBtn = document.getElementById('confirmDeleteBtn');
            confirmInput.value = '';
            confirmInput.classList.remove('valid');
            confirmBtn.disabled = true;
            
            // Add event listener for confirmation input
            confirmInput.oninput = function() {
                const value = this.value.trim().toUpperCase();
                if (value === 'DELETE') {
                    this.classList.add('valid');
                    confirmBtn.disabled = false;
                } else {
                    this.classList.remove('valid');
                    confirmBtn.disabled = true;
                }
            };
            
            document.getElementById('deleteModal').classList.add('active');
            
            // Focus on the input field after a short delay
            setTimeout(() => {
                confirmInput.focus();
            }, 100);
        }

        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.remove('active');
            deleteProductId = null;
            deleteProductName = '';
            
            // Reset confirmation input
            const confirmInput = document.getElementById('deleteConfirmInput');
            const confirmBtn = document.getElementById('confirmDeleteBtn');
            confirmInput.value = '';
            confirmInput.classList.remove('valid');
            confirmBtn.disabled = true;
            confirmInput.oninput = null;
        }

        function executeDelete() {
            if (!deleteProductId) return;
            
            // Double-check the confirmation input
            const confirmValue = document.getElementById('deleteConfirmInput').value.trim().toUpperCase();
            if (confirmValue !== 'DELETE') {
                alert('Please type "DELETE" to confirm deletion.');
                return;
            }
            
            // Create and submit form for deletion
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="delete_product">
                <input type="hidden" name="product_id" value="${deleteProductId}">
                <input type="hidden" name="delete_confirmation" value="${confirmValue}">
            `;
            document.body.appendChild(form);
            form.submit();
        }
        
        function openProductModal() {
            document.getElementById('productModal').classList.add('active');
            document.getElementById('productForm').reset();
            document.getElementById('productId').value = '';
            document.getElementById('productCode').readOnly = false;
            document.getElementById('modalTitle').textContent = 'Add New Product';
            document.getElementById('isActive').checked = false; // Default to inactive
            document.getElementById('showInFrontend').checked = true; // Default to visible in frontend
            
            // Show default tier name field for new products
            document.getElementById('defaultTierNameGroup').style.display = 'block';
            document.getElementById('defaultTierName').required = true;
            
            // Clear the HTML editor and reset to visual mode
            const editor = document.getElementById('productDescriptionEditor');
            editor.innerHTML = '';
            document.getElementById('productDescription').value = '';
            resetEditorToVisualMode();
            
            // Clear date fields and default tier name
            document.getElementById('saleStartDate').value = '';
            document.getElementById('saleEndDate').value = '';
            document.getElementById('defaultTierName').value = '';
        }
        
        function editProduct(product) {
            document.getElementById('modalTitle').textContent = 'Edit Product';
            document.getElementById('formAction').value = 'update_product';
            document.getElementById('productId').value = product.id;
            
            // Load attached products for editing
            loadAttachedProducts(product.id);
            document.getElementById('productCode').value = product.product_code;
            document.getElementById('productCode').readOnly = false;
            document.getElementById('productCategoryId').value = product.category_id || '';
            document.getElementById('productName').value = product.name;
            
            // Set HTML editor content
            const editor = document.getElementById('productDescriptionEditor');
            const description = product.description || '';
            editor.innerHTML = description;
            document.getElementById('productDescription').value = description;
            document.getElementById('basePrice').value = product.base_price;
            document.getElementById('totalStock').value = product.total_stock || '';
            document.getElementById('maxPerReg').value = product.max_per_registration;
            document.getElementById('displayOrder').value = product.display_order;
            
            // Handle date fields - convert from MySQL datetime to HTML datetime-local format
            if (product.sale_start_date) {
                const startDate = new Date(product.sale_start_date);
                document.getElementById('saleStartDate').value = startDate.toISOString().slice(0, 16);
            } else {
                document.getElementById('saleStartDate').value = '';
            }
            
            if (product.sale_end_date) {
                const endDate = new Date(product.sale_end_date);
                document.getElementById('saleEndDate').value = endDate.toISOString().slice(0, 16);
            } else {
                document.getElementById('saleEndDate').value = '';
            }
            
            document.getElementById('isActive').checked = product.is_active == 1;
            document.getElementById('showInFrontend').checked = product.show_in_frontend == 1;
            resetEditorToVisualMode();
            document.getElementById('productModal').classList.add('active');
        }
        
        function closeProductModal() {
            document.getElementById('productModal').classList.remove('active');
            document.getElementById('productCode').readOnly = false;
        }
        
        function toggleProductStatus(productId, newStatus) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="toggle_status">
                <input type="hidden" name="product_id" value="${productId}">
                <input type="hidden" name="is_active" value="${newStatus}">
            `;
            document.body.appendChild(form);
            form.submit();
        }
        
        function duplicateProduct(productId) {
            if (confirm('Are you sure you want to duplicate this product? A copy will be created with "(Copy)" added to the name.')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="duplicate_product">
                    <input type="hidden" name="product_id" value="${productId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        function managePricing(productId) {
            // Find the product card that contains this product ID
            const productCards = document.querySelectorAll('.product-card');
            let productData = null;
            
            productCards.forEach(card => {
                const editButton = card.querySelector('.btn-edit-product');
                if (editButton) {
                    const onclickStr = editButton.getAttribute('onclick');
                    if (onclickStr && onclickStr.includes('editProduct(')) {
                        // Extract the JSON data from the onclick attribute
                        const match = onclickStr.match(/editProduct\((.+)\)$/);
                        if (match) {
                            try {
                                // Decode HTML entities and parse JSON
                                const jsonStr = match[1].replace(/&quot;/g, '"');
                                const product = JSON.parse(jsonStr);
                                
                                if (product.id == productId) {
                                    productData = product;
                                    openPricingModal(productData);
                                    return;
                                }
                            } catch (e) {
                                console.error('Error parsing product data:', e);
                            }
                        }
                    }
                }
            });
            
            if (!productData) {
                // Fallback: try to get basic product info from the card
                productCards.forEach(card => {
                    const pricingButton = card.querySelector('.btn-pricing');
                    if (pricingButton && pricingButton.getAttribute('onclick').includes(productId)) {
                        const productTitle = card.querySelector('.product-title');
                        const productCode = card.querySelector('.product-code');
                        const priceValue = card.querySelector('.price-value');
                        
                        if (productTitle && productCode && priceValue) {
                            productData = {
                                id: productId,
                                name: productTitle.textContent,
                                product_code: productCode.textContent,
                                base_price: priceValue.textContent.replace('$', '').replace(',', '')
                            };
                            openPricingModal(productData);
                            return;
                        }
                    }
                });
            }
            
            if (!productData) {
                alert('Error: Could not load product data for pricing management.');
            }
        }
        
        // New Pricing Modal Functions
        function openPricingModal(product) {
            document.getElementById('pricingProductId').value = product.id;
            document.getElementById('pricingProductName').textContent = product.name;
            document.getElementById('pricingBasePrice').value = product.base_price;
            
            // Load existing pricing tiers
            loadNewPricingTiers(product.id);
            
            document.getElementById('pricingModal').classList.add('active');
        }
        
        function closePricingModal() {
            document.getElementById('pricingModal').classList.remove('active');
        }
        
        function formatDateForInput(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day}T${hours}:${minutes}`;
        }
        
        function loadNewPricingTiers(productId) {
            const tiersContainer = document.getElementById('newPricingTiers');
            const emptyState = document.getElementById('emptyTiersState');
            
            // Show loading state
            tiersContainer.innerHTML = '<div style="text-align: center; padding: 2rem; color: #6b7280;">Loading tiers...</div>';
            emptyState.classList.remove('show');
            
            // Load existing tiers from API
            fetch(`product_pricing_api.php?action=get_tiers&product_id=${productId}&t=${Date.now()}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    return response.text();
                })
                .then(text => {
                    console.log('Raw API response:', text);
                    try {
                        const data = JSON.parse(text);
                        console.log('Parsed data:', data);
                        
                        tiersContainer.innerHTML = '';
                        
                        if (data.success && data.tiers && data.tiers.length > 0) {
                            data.tiers.forEach((tier, index) => {
                                addNewPricingTierCard(tier, index + 1);
                            });
                            emptyState.classList.remove('show');
                        } else {
                            emptyState.classList.add('show');
                        }
                    } catch (parseError) {
                        console.error('Error parsing JSON:', parseError);
                        tiersContainer.innerHTML = '';
                        emptyState.classList.add('show');
                    }
                })
                .catch(error => {
                    console.error('Error loading pricing tiers:', error);
                    tiersContainer.innerHTML = '';
                    emptyState.classList.add('show');
                });
        }
        
        function addNewPricingTier() {
            const tiersContainer = document.getElementById('newPricingTiers');
            const emptyState = document.getElementById('emptyTiersState');
            const tierCount = tiersContainer.children.length + 1;
            
            addNewPricingTierCard(null, tierCount);
            emptyState.classList.remove('show');
        }
        
        function addNewPricingTierCard(tierData = null, tierNumber = 1) {
            const tiersContainer = document.getElementById('newPricingTiers');
            const tierCard = document.createElement('div');
            tierCard.className = 'new-pricing-tier-card';
            
            const currentDate = formatDateForInput(new Date());
            const futureDate = formatDateForInput(new Date(Date.now() + 30 * 24 * 60 * 60 * 1000));
            
            const tierName = tierData ? tierData.pricing_tier : `Tier ${tierNumber}`;
            const tierPrice = tierData ? tierData.price : '';
            const validFrom = tierData && tierData.valid_from ? formatDateForInput(new Date(tierData.valid_from)) : currentDate;
            const validUntil = tierData && tierData.valid_until ? formatDateForInput(new Date(tierData.valid_until)) : futureDate;
            
            tierCard.innerHTML = `
                <div class="new-pricing-tier-header">
                    <input type="text" class="new-pricing-tier-name" value="${tierName}" placeholder="Tier Name">
                    <button type="button" class="new-pricing-tier-remove" onclick="removeNewPricingTier(this)">
                        Remove
                    </button>
                </div>
                <div class="new-pricing-tier-fields">
                    <div class="new-pricing-field">
                        <label>Price (RM)</label>
                        <input type="number" step="0.01" min="0" value="${tierPrice}" placeholder="0.00" class="new-tier-price-input">
                    </div>
                    <div class="new-pricing-field">
                        <label>Valid From</label>
                        <input type="datetime-local" value="${validFrom}" class="new-tier-from-input">
                    </div>
                    <div class="new-pricing-field">
                        <label>Valid Until</label>
                        <input type="datetime-local" value="${validUntil}" class="new-tier-until-input">
                    </div>
                </div>
            `;
            
            tiersContainer.appendChild(tierCard);
        }
        
        function removeNewPricingTier(button) {
            const tierCard = button.closest('.new-pricing-tier-card');
            const tiersContainer = document.getElementById('newPricingTiers');
            const emptyState = document.getElementById('emptyTiersState');
            
            tierCard.remove();
            
            // Show empty state if no tiers left
            if (tiersContainer.children.length === 0) {
                emptyState.classList.add('show');
            }
        }
        
        function saveNewPricingTiers() {
            const productId = document.getElementById('pricingProductId').value;
            const basePrice = document.getElementById('pricingBasePrice').value;
            const tiers = [];
            
            // Validate base price
            if (!basePrice || parseFloat(basePrice) < 0) {
                alert('Please enter a valid base price.');
                return;
            }
            
            // Collect tier data
            document.querySelectorAll('.new-pricing-tier-card').forEach(tierCard => {
                const nameInput = tierCard.querySelector('.new-pricing-tier-name');
                const priceInput = tierCard.querySelector('.new-tier-price-input');
                const fromInput = tierCard.querySelector('.new-tier-from-input');
                const untilInput = tierCard.querySelector('.new-tier-until-input');
                
                if (nameInput.value.trim() && priceInput.value && parseFloat(priceInput.value) >= 0) {
                    tiers.push({
                        name: nameInput.value.trim(),
                        price: parseFloat(priceInput.value),
                        valid_from: fromInput.value || null,
                        valid_until: untilInput.value || null
                    });
                }
            });
            
            // Show saving state
            const saveBtn = document.querySelector('.new-btn-primary');
            const originalText = saveBtn.innerHTML;
            saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
            saveBtn.disabled = true;
            
            // Save pricing data
            fetch('product_pricing_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'save_pricing',
                    product_id: productId,
                    base_price: parseFloat(basePrice),
                    tiers: tiers
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message in page instead of popup
                    showNotification('Pricing saved successfully!', 'success');
                    closePricingModal();
                    location.reload(); // Refresh to show updated pricing
                } else {
                    showNotification('Error saving pricing: ' + (data.message || 'Unknown error'), 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('Error saving pricing. Please try again.', 'error');
            })
            .finally(() => {
                // Restore button state
                saveBtn.innerHTML = originalText;
                saveBtn.disabled = false;
            });
        }
        
        // Category Management Functions
        function openCategoryModal() {
            document.getElementById('categoryModal').classList.add('active');
        }
        
        function closeCategoryModal() {
            document.getElementById('categoryModal').classList.remove('active');
        }
        
        function openCategoryForm(categoryId = null) {
            const modal = document.getElementById('categoryFormModal');
            const title = document.getElementById('categoryFormTitle');
            const action = document.getElementById('categoryAction');
            const form = document.getElementById('categoryForm');
            const activeGroup = document.getElementById('activeCheckboxGroup');
            
            if (categoryId) {
                // Edit mode
                title.textContent = 'Edit Category';
                action.value = 'update_category';
                document.getElementById('categoryId').value = categoryId;
                activeGroup.style.display = 'block';
                
                // Load category data (you'd fetch this from server in a real app)
                // For now, we'll use a simple approach
                loadCategoryData(categoryId);
            } else {
                // Create mode
                title.textContent = 'Create New Category';
                action.value = 'create_category';
                document.getElementById('categoryId').value = '';
                activeGroup.style.display = 'none';
                form.reset();
            }
            
            modal.classList.add('active');
        }
        
        function closeCategoryForm() {
            document.getElementById('categoryFormModal').classList.remove('active');
            document.getElementById('categoryForm').reset();
        }
        
        function editCategory(categoryId) {
            closeCategoryModal();
            openCategoryForm(categoryId);
        }
        
        function deleteCategory(categoryId) {
            // First check if category has products assigned
            fetch('product_pricing_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'check_category_products',
                    category_id: categoryId
                })
            })
            .then(response => response.json())
            .then(data => {
                console.log('API Response:', data);
                if (data.success && data.product_count > 0) {
                    alert(`Cannot delete this category because it has ${data.product_count} product(s) assigned to it. Please move the products to another category first.`);
                    return;
                }
                
                if (!data.success) {
                    console.error('API Error:', data.message);
                    alert('Error checking category: ' + data.message);
                    return;
                }
                
                // If no products, proceed with deletion confirmation
                if (confirm('Are you sure you want to delete this category? This action cannot be undone.')) {
                    const formData = new FormData();
                    formData.append('action', 'delete_category');
                    formData.append('category_id', categoryId);
                    
                    fetch('product-catalog.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.text())
                    .then(() => {
                        location.reload();
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Error deleting category');
                    });
                }
            })
            .catch(error => {
                console.error('Error checking category:', error);
                alert('Error checking category status. Please try again or contact support.');
                return;
            });
        }
        
        function loadCategoryData(categoryId) {
            // In a real application, you'd make an AJAX call to get category data
            // For now, we'll extract data from the existing DOM
            const categoryItems = document.querySelectorAll('.category-item');
            categoryItems.forEach(item => {
                const editBtn = item.querySelector('.btn-edit');
                if (editBtn && editBtn.getAttribute('onclick').includes(categoryId)) {
                    const name = item.querySelector('h4').textContent;
                    const description = item.querySelector('p').textContent;
                    const orderText = item.querySelector('.display-order').textContent;
                    const order = orderText.replace('Order: ', '');
                    const isActive = item.classList.contains('active');
                    
                    document.getElementById('categoryName').value = name;
                    document.getElementById('categoryDescription').value = description;
                    document.getElementById('categoryDisplayOrder').value = order;
                    document.getElementById('categoryIsActive').checked = isActive;
                }
            });
        }
        
        // HTML Editor Functions
        let isHtmlViewMode = false;
        
        function formatText(command) {
            if (isHtmlViewMode) return; // Disable formatting in HTML mode
            
            const editor = document.getElementById('productDescriptionEditor');
            editor.focus();
            
            if (command === 'createLink') {
                const url = prompt('Enter URL:');
                if (url) {
                    document.execCommand(command, false, url);
                }
            } else {
                document.execCommand(command, false, null);
            }
            
            // Update hidden textarea
            updateHiddenTextarea();
        }
        
        
        function debugFormSubmission(event) {
            const formData = new FormData(event.target);
            console.log('Form submission data:');
            for (let [key, value] of formData.entries()) {
                console.log(`${key}: ${value}`);
            }
            // Continue with normal form submission
            return true;
        }
        
        function toggleHtmlView() {
            const editor = document.getElementById('productDescriptionEditor');
            const toggleBtn = document.getElementById('htmlToggleBtn');
            const formatBtns = document.querySelectorAll('.editor-btn:not(#htmlToggleBtn)');
            
            if (!isHtmlViewMode) {
                // Switch to HTML view
                const htmlContent = editor.innerHTML;
                editor.style.fontFamily = 'monospace';
                editor.style.fontSize = '13px';
                editor.style.whiteSpace = 'pre-wrap';
                editor.textContent = htmlContent;
                
                toggleBtn.style.backgroundColor = '#007cba';
                toggleBtn.style.color = 'white';
                toggleBtn.title = 'Switch to Visual Editor';
                
                // Disable formatting buttons
                formatBtns.forEach(btn => {
                    btn.style.opacity = '0.5';
                    btn.style.pointerEvents = 'none';
                });
                
                isHtmlViewMode = true;
            } else {
                // Switch to visual view
                const htmlContent = editor.textContent;
                editor.style.fontFamily = '';
                editor.style.fontSize = '';
                editor.style.whiteSpace = '';
                editor.innerHTML = htmlContent;
                
                toggleBtn.style.backgroundColor = '';
                toggleBtn.style.color = '';
                toggleBtn.title = 'Toggle HTML View';
                
                // Enable formatting buttons
                formatBtns.forEach(btn => {
                    btn.style.opacity = '';
                    btn.style.pointerEvents = '';
                });
                
                isHtmlViewMode = false;
            }
            
            // Update hidden textarea
            updateHiddenTextarea();
        }
        
        function updateHiddenTextarea() {
            const editor = document.getElementById('productDescriptionEditor');
            const textarea = document.getElementById('productDescription');
            textarea.value = editor.innerHTML;
        }
        
        function resetEditorToVisualMode() {
            if (isHtmlViewMode) {
                const editor = document.getElementById('productDescriptionEditor');
                const toggleBtn = document.getElementById('htmlToggleBtn');
                const formatBtns = document.querySelectorAll('.editor-btn:not(#htmlToggleBtn)');
                
                // Reset editor styles
                editor.style.fontFamily = '';
                editor.style.fontSize = '';
                editor.style.whiteSpace = '';
                
                // Reset button styles
                toggleBtn.style.backgroundColor = '';
                toggleBtn.style.color = '';
                toggleBtn.title = 'Toggle HTML View';
                
                // Enable formatting buttons
                formatBtns.forEach(btn => {
                    btn.style.opacity = '';
                    btn.style.pointerEvents = '';
                });
                
                isHtmlViewMode = false;
            }
        }
        
        // Initialize editor event listeners
        document.addEventListener('DOMContentLoaded', function() {
            const editor = document.getElementById('productDescriptionEditor');
            if (editor) {
                editor.addEventListener('input', updateHiddenTextarea);
                editor.addEventListener('paste', function(e) {
                    // Allow paste but clean up formatting
                    setTimeout(updateHiddenTextarea, 10);
                });
            }
            
            // Form submission handler
            const productForm = document.getElementById('productForm');
            if (productForm) {
                productForm.addEventListener('submit', function(e) {
                    updateHiddenTextarea();
                    // Serialize attached products data
                    document.getElementById('attachedProductsData').value = serializeAttachedProducts();
                });
            }
        });
        
        // Attached Products Management
        let attachedProductsData = [];
        
        function addAttachedProduct() {
            const container = document.getElementById('attachedProductsList');
            const index = attachedProductsData.length;
            
            const attachmentDiv = document.createElement('div');
            attachmentDiv.className = 'attached-product-item';
            attachmentDiv.dataset.index = index;
            
            attachmentDiv.innerHTML = `
                <div class="attached-product-row">
                    <div class="attached-product-select">
                        <label>Product</label>
                        <select onchange="updateAttachedProduct(${index}, 'product_id', this.value)" required>
                            <option value="">Select a product...</option>
                            <?php foreach ($products as $product): ?>
                                <option value="<?php echo $product['id']; ?>">
                                    <?php echo htmlspecialchars($product['name']); ?> (<?php echo $product['product_code']; ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="attached-product-quantity">
                        <label>Quantity</label>
                        <input type="number" min="1" value="1" onchange="updateAttachedProduct(${index}, 'quantity', this.value)" required>
                    </div>
                    <div class="attached-product-notes">
                        <label>Notes (optional)</label>
                        <input type="text" placeholder="e.g., Included with package" onchange="updateAttachedProduct(${index}, 'notes', this.value)">
                    </div>
                    <div class="attached-product-actions">
                        <button type="button" onclick="removeAttachedProduct(${index})" class="btn-remove-attachment">×</button>
                    </div>
                </div>
            `;
            
            container.appendChild(attachmentDiv);
            
            // Initialize data
            attachedProductsData[index] = {
                product_id: '',
                quantity: 1,
                notes: ''
            };
        }
        
        function updateAttachedProduct(index, field, value) {
            if (attachedProductsData[index]) {
                attachedProductsData[index][field] = value;
            }
        }
        
        function removeAttachedProduct(index) {
            const item = document.querySelector(`[data-index="${index}"]`);
            if (item) {
                item.remove();
                delete attachedProductsData[index];
            }
        }
        
        function loadAttachedProducts(productId) {
            if (!productId) {
                clearAttachedProducts();
                return;
            }
            
            // Fetch attached products via AJAX
            fetch(`product_api.php?action=get_attached_products&product_id=${productId}`)
                .then(response => response.json())
                .then(data => {
                    clearAttachedProducts();
                    if (data.success && data.attachments) {
                        data.attachments.forEach((attachment, index) => {
                            addAttachedProduct();
                            const item = document.querySelector(`[data-index="${index}"]`);
                            if (item) {
                                item.querySelector('select').value = attachment.attached_product_id;
                                item.querySelector('input[type="number"]').value = attachment.quantity;
                                item.querySelector('input[type="text"]').value = attachment.notes || '';
                                
                                attachedProductsData[index] = {
                                    product_id: attachment.attached_product_id,
                                    quantity: attachment.quantity,
                                    notes: attachment.notes || ''
                                };
                            }
                        });
                    }
                })
                .catch(error => console.error('Error loading attached products:', error));
        }
        
        function clearAttachedProducts() {
            const container = document.getElementById('attachedProductsList');
            container.innerHTML = '';
            attachedProductsData = [];
        }
        
        function serializeAttachedProducts() {
            const validAttachments = attachedProductsData.filter(item => 
                item && item.product_id && item.quantity > 0
            );
            return JSON.stringify(validAttachments);
        }

        // Disabled: Close modal when clicking outside
        // window.onclick = function(event) {
        //     const modal = document.getElementById('productModal');
        //     if (event.target === modal) {
        //         closeProductModal();
        //     }
        // }
    </script>

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