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

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

// Calculate the correct path using multiple fallbacks
// Current file: /HMSPOS/pos/products/edit.php
// Need to go up to: /HMSPOS/
$base_path = null;

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

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

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

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/auth.php';

// Load helpers if they exist
if (file_exists($base_path . '/config/helpers.php')) {
    require_once $base_path . '/config/helpers.php';
}
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}
if (file_exists($base_path . '/config/constants.php')) {
    require_once $base_path . '/config/constants.php';
}

// Require authentication
require_auth();

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

// Define audit constants if not defined
if (!defined('AUDIT_UPDATE')) {
    define('AUDIT_UPDATE', 'update');
}

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

if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        if (is_array($data)) {
            return array_map('sanitize_input', $data);
        }
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('pos.products.manage');
// }

// Set page title
$page_title = 'Edit Product';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

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

// Get product ID from URL
$product_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$product_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid product ID');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get product data
$product = null;
try {
    $product = db_fetch_one("SELECT * FROM pos_products WHERE product_id = ?", [$product_id]);
} catch (Exception $e) {
    error_log("Error fetching product: " . $e->getMessage());
}

if (!$product) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Product not found');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

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

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

// Get tax rates for dropdown
$tax_rates = [];
try {
    $tax_rates = db_fetch_all("SELECT tax_id, tax_name, tax_rate FROM tax_rates WHERE is_active = 1 ORDER BY tax_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching tax rates: " . $e->getMessage());
}

// Handle form submission
$errors = [];
$form_data = [
    'product_code' => $product['product_code'] ?? '',
    'barcode' => $product['barcode'] ?? '',
    'product_name' => $product['product_name'] ?? '',
    'description' => $product['description'] ?? '',
    'category_id' => $product['category_id'] ?? 0,
    'outlet_id' => $product['outlet_id'] ?? null,
    'unit_price' => $product['unit_price'] ?? 0,
    'cost_price' => $product['cost_price'] ?? null,
    'tax_id' => $product['tax_id'] ?? null,
    'tax_inclusive' => $product['tax_inclusive'] ?? 0,
    'stock_item' => $product['stock_item'] ?? 0,
    'current_stock' => $product['current_stock'] ?? 0,
    'min_stock' => $product['min_stock'] ?? 0,
    'max_stock' => $product['max_stock'] ?? null,
    'unit_of_measure' => $product['unit_of_measure'] ?? '',
    'track_serial' => $product['track_serial'] ?? 0,
    'is_active' => $product['is_active'] ?? 1
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = true;
    if (function_exists('verify_csrf_token')) {
        $csrf_name = defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token';
        $token = $_POST[$csrf_name] ?? '';
        if (!verify_csrf_token($token)) {
            $csrf_valid = false;
            $errors[] = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        // Get and validate input
        $form_data['product_code'] = isset($_POST['product_code']) ? strtoupper(trim($_POST['product_code'])) : '';
        $form_data['barcode'] = $_POST['barcode'] ?? '';
        $form_data['product_name'] = $_POST['product_name'] ?? '';
        $form_data['description'] = $_POST['description'] ?? '';
        $form_data['category_id'] = (int)($_POST['category_id'] ?? 0);
        $form_data['outlet_id'] = !empty($_POST['outlet_id']) ? (int)$_POST['outlet_id'] : null;
        $form_data['unit_price'] = (float)($_POST['unit_price'] ?? 0);
        $form_data['cost_price'] = !empty($_POST['cost_price']) ? (float)$_POST['cost_price'] : null;
        $form_data['tax_id'] = !empty($_POST['tax_id']) ? (int)$_POST['tax_id'] : null;
        $form_data['tax_inclusive'] = isset($_POST['tax_inclusive']) ? 1 : 0;
        $form_data['stock_item'] = isset($_POST['stock_item']) ? 1 : 0;
        $form_data['current_stock'] = (float)($_POST['current_stock'] ?? 0);
        $form_data['min_stock'] = (float)($_POST['min_stock'] ?? 0);
        $form_data['max_stock'] = !empty($_POST['max_stock']) ? (float)$_POST['max_stock'] : null;
        $form_data['unit_of_measure'] = $_POST['unit_of_measure'] ?? '';
        $form_data['track_serial'] = isset($_POST['track_serial']) ? 1 : 0;
        $form_data['is_active'] = isset($_POST['is_active']) ? 1 : 0;
        
        // Validate required fields
        if (empty($form_data['product_code'])) {
            $errors[] = 'Product code is required';
        } elseif (strlen($form_data['product_code']) > 50) {
            $errors[] = 'Product code must not exceed 50 characters';
        }
        
        if (empty($form_data['product_name'])) {
            $errors[] = 'Product name is required';
        } elseif (strlen($form_data['product_name']) > 255) {
            $errors[] = 'Product name must not exceed 255 characters';
        }
        
        if (!$form_data['category_id']) {
            $errors[] = 'Category is required';
        }
        
        if ($form_data['unit_price'] <= 0) {
            $errors[] = 'Unit price must be greater than 0';
        }
        
        if ($form_data['stock_item'] && $form_data['current_stock'] < 0) {
            $errors[] = 'Current stock cannot be negative';
        }
        
        if ($form_data['max_stock'] && $form_data['max_stock'] < $form_data['min_stock']) {
            $errors[] = 'Maximum stock must be greater than minimum stock';
        }
        
        // Check uniqueness
        if (empty($errors)) {
            try {
                $exists = (int)db_fetch_value(
                    "SELECT COUNT(*) FROM pos_products WHERE product_code = ? AND product_id != ?", 
                    [$form_data['product_code'], $product_id]
                ) ?: 0;
                if ($exists > 0) {
                    $errors[] = 'Product code already exists';
                }
                
                if (!empty($form_data['barcode'])) {
                    $exists = (int)db_fetch_value(
                        "SELECT COUNT(*) FROM pos_products WHERE barcode = ? AND product_id != ?", 
                        [$form_data['barcode'], $product_id]
                    ) ?: 0;
                    if ($exists > 0) {
                        $errors[] = 'Barcode already exists';
                    }
                }
            } catch (Exception $e) {
                error_log("Error checking uniqueness: " . $e->getMessage());
            }
        }
        
        // Update product
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                // Check if stock changed
                $stock_changed = (abs($form_data['current_stock'] - ($product['current_stock'] ?? 0)) > 0.001);
                
                $update_data = [
                    'product_code' => $form_data['product_code'],
                    'barcode' => $form_data['barcode'] ?: null,
                    'product_name' => $form_data['product_name'],
                    'description' => $form_data['description'] ?: null,
                    'category_id' => $form_data['category_id'],
                    'outlet_id' => $form_data['outlet_id'],
                    'unit_price' => $form_data['unit_price'],
                    'cost_price' => $form_data['cost_price'],
                    'tax_id' => $form_data['tax_id'],
                    'tax_inclusive' => $form_data['tax_inclusive'],
                    'stock_item' => $form_data['stock_item'],
                    'current_stock' => $form_data['current_stock'],
                    'min_stock' => $form_data['min_stock'],
                    'max_stock' => $form_data['max_stock'],
                    'unit_of_measure' => $form_data['unit_of_measure'] ?: null,
                    'track_serial' => $form_data['track_serial'],
                    'is_active' => $form_data['is_active']
                ];
                
                if (function_exists('db_update')) {
                    db_update('pos_products', $update_data, 'product_id = ?', [$product_id]);
                } else {
                    // Fallback direct update
                    $pdo = get_db_connection();
                    $sql = "UPDATE pos_products SET 
                            product_code = ?, barcode = ?, product_name = ?, description = ?,
                            category_id = ?, outlet_id = ?, unit_price = ?, cost_price = ?,
                            tax_id = ?, tax_inclusive = ?, stock_item = ?, current_stock = ?,
                            min_stock = ?, max_stock = ?, unit_of_measure = ?, track_serial = ?,
                            is_active = ?
                            WHERE product_id = ?";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([
                        $form_data['product_code'],
                        $form_data['barcode'] ?: null,
                        $form_data['product_name'],
                        $form_data['description'] ?: null,
                        $form_data['category_id'],
                        $form_data['outlet_id'],
                        $form_data['unit_price'],
                        $form_data['cost_price'],
                        $form_data['tax_id'],
                        $form_data['tax_inclusive'],
                        $form_data['stock_item'],
                        $form_data['current_stock'],
                        $form_data['min_stock'],
                        $form_data['max_stock'],
                        $form_data['unit_of_measure'] ?: null,
                        $form_data['track_serial'],
                        $form_data['is_active'],
                        $product_id
                    ]);
                }
                
                // Record stock adjustment if changed
                if ($stock_changed) {
                    $quantity_diff = $form_data['current_stock'] - ($product['current_stock'] ?? 0);
                    
                    if (abs($quantity_diff) > 0.001 && function_exists('db_insert')) {
                        try {
                            db_insert('stock_movements', [
                                'product_id' => $product_id,
                                'movement_type' => 'adjustment',
                                'quantity' => $quantity_diff,
                                'reference_type' => 'manual_adjustment',
                                'notes' => 'Stock adjusted during product edit',
                                'created_by' => $user_id,
                                'created_at' => date('Y-m-d H:i:s')
                            ]);
                        } catch (Exception $e) {
                            error_log("Error recording stock movement: " . $e->getMessage());
                        }
                    }
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, 'update', 'pos_products', $product_id, $product, $update_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Product updated successfully');
                }
                
                // Redirect
                if (function_exists('redirect')) {
                    redirect('view.php?id=' . $product_id);
                } else {
                    header('Location: view.php?id=' . $product_id);
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to update product: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Product update failed: " . $e->getMessage(), 'ERROR');
                } else {
                    error_log("Product update failed: " . $e->getMessage());
                }
            }
        }
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Edit Product</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Edit Product</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Edit Product: <?php echo escape_html($product['product_name'] ?? ''); ?></h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/pos/dashboard.php">POS</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Products</a></li>
                    <li class="breadcrumb-item"><a href="view.php?id=<?php echo $product_id; ?>">View</a></li>
                    <li class="breadcrumb-item active">Edit</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <!-- Error Messages -->
                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        <strong>Please fix the following errors:</strong>
                        <ul class="mt-2 mb-0">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Edit Form -->
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit me-1"></i>
                            Edit Product
                        </h3>
                    </div>
                    
                    <form method="POST" id="editForm">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                        <?php endif; ?>
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h5>Basic Information</h5>
                                    
                                    <div class="mb-3">
                                        <label for="product_code" class="form-label">Product Code <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="product_code" name="product_code" 
                                               value="<?php echo escape_html($form_data['product_code']); ?>" 
                                               maxlength="50" required>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="barcode" class="form-label">Barcode (UPC/EAN)</label>
                                        <input type="text" class="form-control" id="barcode" name="barcode" 
                                               value="<?php echo escape_html($form_data['barcode']); ?>">
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="product_name" class="form-label">Product Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="product_name" name="product_name" 
                                               value="<?php echo escape_html($form_data['product_name']); ?>" 
                                               maxlength="255" required>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="description" class="form-label">Description</label>
                                        <textarea class="form-control" id="description" name="description" rows="3"><?php echo escape_html($form_data['description']); ?></textarea>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <h5>Classification</h5>
                                    
                                    <div class="mb-3">
                                        <label for="category_id" class="form-label">Category <span class="text-danger">*</span></label>
                                        <select class="form-select" id="category_id" name="category_id" required>
                                            <option value="">Select Category</option>
                                            <?php foreach ($categories as $cat): ?>
                                                <option value="<?php echo $cat['category_id'] ?? 0; ?>" <?php echo $form_data['category_id'] == ($cat['category_id'] ?? 0) ? 'selected' : ''; ?>>
                                                    <?php echo escape_html($cat['category_name'] ?? ''); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="outlet_id" class="form-label">Specific Outlet</label>
                                        <select class="form-select" id="outlet_id" name="outlet_id">
                                            <option value="">All Outlets</option>
                                            <?php foreach ($outlets as $outlet): ?>
                                                <option value="<?php echo $outlet['outlet_id'] ?? 0; ?>" <?php echo $form_data['outlet_id'] == ($outlet['outlet_id'] ?? 0) ? 'selected' : ''; ?>>
                                                    <?php echo escape_html($outlet['outlet_name'] ?? ''); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="row mt-4">
                                <div class="col-md-6">
                                    <h5>Pricing</h5>
                                    
                                    <div class="mb-3">
                                        <label for="unit_price" class="form-label">Unit Price <span class="text-danger">*</span></label>
                                        <div class="input-group">
                                            <span class="input-group-text"><?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?></span>
                                            <input type="number" class="form-control" id="unit_price" name="unit_price" 
                                                   value="<?php echo $form_data['unit_price']; ?>" step="0.01" min="0" required>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="cost_price" class="form-label">Cost Price</label>
                                        <div class="input-group">
                                            <span class="input-group-text"><?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?></span>
                                            <input type="number" class="form-control" id="cost_price" name="cost_price" 
                                                   value="<?php echo $form_data['cost_price']; ?>" step="0.01" min="0">
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="tax_id" class="form-label">Tax Rate</label>
                                        <select class="form-select" id="tax_id" name="tax_id">
                                            <option value="">No Tax</option>
                                            <?php foreach ($tax_rates as $tax): ?>
                                                <option value="<?php echo $tax['tax_id'] ?? 0; ?>" <?php echo $form_data['tax_id'] == ($tax['tax_id'] ?? 0) ? 'selected' : ''; ?>>
                                                    <?php echo escape_html($tax['tax_name'] ?? ''); ?> (<?php echo $tax['tax_rate'] ?? 0; ?>%)
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <div class="form-check">
                                            <input type="checkbox" class="form-check-input" id="tax_inclusive" name="tax_inclusive"
                                                   <?php echo $form_data['tax_inclusive'] ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="tax_inclusive">Price includes tax</label>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <h5>Inventory</h5>
                                    
                                    <div class="mb-3">
                                        <div class="form-check">
                                            <input type="checkbox" class="form-check-input" id="stock_item" name="stock_item"
                                                   <?php echo $form_data['stock_item'] ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="stock_item">Track Inventory</label>
                                        </div>
                                    </div>
                                    
                                    <div id="stock_fields" style="<?php echo !$form_data['stock_item'] ? 'display: none;' : ''; ?>">
                                        <div class="mb-3">
                                            <label for="current_stock" class="form-label">Current Stock</label>
                                            <input type="number" class="form-control" id="current_stock" name="current_stock" 
                                                   value="<?php echo $form_data['current_stock']; ?>" step="0.01" min="0">
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label for="min_stock" class="form-label">Min Stock</label>
                                                    <input type="number" class="form-control" id="min_stock" name="min_stock" 
                                                           value="<?php echo $form_data['min_stock']; ?>" step="0.01" min="0">
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label for="max_stock" class="form-label">Max Stock</label>
                                                    <input type="number" class="form-control" id="max_stock" name="max_stock" 
                                                           value="<?php echo $form_data['max_stock']; ?>" step="0.01" min="0">
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label for="unit_of_measure" class="form-label">Unit</label>
                                                    <input type="text" class="form-control" id="unit_of_measure" name="unit_of_measure" 
                                                           value="<?php echo escape_html($form_data['unit_of_measure']); ?>">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <div class="form-check">
                                                <input type="checkbox" class="form-check-input" id="track_serial" name="track_serial"
                                                       <?php echo $form_data['track_serial'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="track_serial">Track Serial Numbers</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row mt-3">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <div class="form-check form-switch">
                                            <input type="checkbox" class="form-check-input" id="is_active" name="is_active"
                                                   <?php echo $form_data['is_active'] ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="is_active">Active</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-save me-1"></i> Update Product
                            </button>
                            <a href="view.php?id=<?php echo $product_id; ?>" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Toggle stock fields
    $('#stock_item').on('change', function() {
        if ($(this).is(':checked')) {
            $('#stock_fields').slideDown();
        } else {
            $('#stock_fields').slideUp();
        }
    });
    
    // Auto-capitalize product code
    $('#product_code').on('input', function() {
        this.value = this.value.toUpperCase();
    });
    
    // Check code availability
    let codeTimeout;
    $('#product_code').on('input', function() {
        clearTimeout(codeTimeout);
        const code = $(this).val();
        const originalCode = '<?php echo addslashes($product['product_code'] ?? ''); ?>';
        
        if (code.length < 2 || code === originalCode) return;
        
        codeTimeout = setTimeout(function() {
            $.ajax({
                url: '/HMSPOS/api/check-product-code.php',
                method: 'GET',
                data: { code: code, exclude: <?php echo $product_id; ?> },
                dataType: 'json',
                success: function(response) {
                    const $code = $('#product_code');
                    if (response.exists) {
                        $code.addClass('is-invalid');
                        if ($code.next('.invalid-feedback').length === 0) {
                            $code.after('<div class="invalid-feedback">Product code already exists</div>');
                        }
                    } else {
                        $code.removeClass('is-invalid');
                        $code.next('.invalid-feedback').remove();
                    }
                },
                error: function() {
                    console.error('Failed to check code availability');
                }
            });
        }, 500);
    });
    
    // Check barcode availability
    let barcodeTimeout;
    $('#barcode').on('input', function() {
        clearTimeout(barcodeTimeout);
        const barcode = $(this).val();
        const originalBarcode = '<?php echo addslashes($product['barcode'] ?? ''); ?>';
        
        if (barcode.length < 5 || barcode === originalBarcode) return;
        
        barcodeTimeout = setTimeout(function() {
            $.ajax({
                url: '/HMSPOS/api/check-barcode.php',
                method: 'GET',
                data: { barcode: barcode, exclude: <?php echo $product_id; ?> },
                dataType: 'json',
                success: function(response) {
                    const $barcode = $('#barcode');
                    if (response.exists) {
                        $barcode.addClass('is-invalid');
                        if ($barcode.next('.invalid-feedback').length === 0) {
                            $barcode.after('<div class="invalid-feedback">Barcode already exists</div>');
                        }
                    } else {
                        $barcode.removeClass('is-invalid');
                        $barcode.next('.invalid-feedback').remove();
                    }
                },
                error: function() {
                    console.error('Failed to check barcode availability');
                }
            });
        }, 500);
    });
});
</script>

<style>
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-3 { margin-top: 1rem; }
.mt-4 { margin-top: 1.5rem; }
.input-group-text { background-color: #e9ecef; }
</style>

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