<?php
// Ensure session is started only once
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

// Ensure user is logged in
if (!isset($_SESSION['user'])) {
    header("Location: ../auth/login.php");
    exit;
}

$user = $_SESSION['user'];
$shop_id = $user['shop_id']; // current shop

$message = '';
$sku = $name = $generic_name = $unit = $category = '';
$vat_percent = $buying_price = $selling_price = 0;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and trim inputs
    $sku = !empty(trim($_POST['sku'])) ? strtoupper(trim($_POST['sku'])) : NULL;
    $name = trim($_POST['name']);
    $generic_name = trim($_POST['generic_name']);
    $unit = trim($_POST['unit']);
    $category = trim($_POST['category']);
    $vat_percent = floatval($_POST['vat_percent']); // ensure numeric
    $buying_price = floatval($_POST['buying_price']); // ensure numeric
    $selling_price = floatval($_POST['selling_price']); // NEW: selling price field

    // Check for custom unit/category
    if (!empty($_POST['custom_unit'])) {
        $unit = trim($_POST['custom_unit']);
    }
    if (!empty($_POST['custom_category'])) {
        $category = trim($_POST['custom_category']);
    }

    // Validation
    if (empty($name)) {
        $message = "<div class='alert alert-danger'>Product name is required.</div>";
    } elseif ($vat_percent < 0 || $vat_percent > 100) {
        $message = "<div class='alert alert-danger'>VAT percent must be between 0 and 100.</div>";
    } elseif ($buying_price < 0) {
        $message = "<div class='alert alert-danger'>Buying price cannot be negative.</div>";
    } elseif ($selling_price < 0) {
        $message = "<div class='alert alert-danger'>Selling price cannot be negative.</div>";
    } elseif ($selling_price > 0 && $buying_price > 0 && $selling_price < $buying_price) {
        $message = "<div class='alert alert-warning'>⚠️ Selling price is less than buying price. This may result in loss.</div>";
    } else {
        // Auto-generate SKU if empty
        if ($sku === NULL) {
            $base = strtoupper(substr(preg_replace("/[^a-zA-Z]/", "", $name), 0, 3));
            do {
                $sku = $base . '-' . rand(100, 999);
                $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM products WHERE sku = ? AND shop_id = ?");
                $stmt_check->execute([$sku, $shop_id]);
                $count = $stmt_check->fetchColumn();
            } while ($count > 0); // ensure uniqueness
        } else {
            // Check for existing SKU (including NULL values)
            $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM products WHERE sku = ? AND shop_id = ?");
            $stmt_check->execute([$sku, $shop_id]);
            if ($stmt_check->fetchColumn() > 0) {
                $message = "<div class='alert alert-danger'>SKU already exists. Please choose another.</div>";
            }
        }

        // Insert product if no errors so far
        if (empty($message)) {
            try {
                // FIXED: Using only vat_percent, NOT vat column
                $stmt = $pdo->prepare("
                    INSERT INTO products 
                    (sku, name, generic_name, unit, category, vat_percent, 
                     buying_price, selling_price, shop_id)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $sku, 
                    $name, 
                    $generic_name, 
                    $unit, 
                    $category, 
                    $vat_percent,
                    $buying_price, 
                    $selling_price, 
                    $shop_id
                ]);

                $message = "<div class='alert alert-success'>Product added successfully! SKU: <strong>" . ($sku ?? 'Auto-generated') . "</strong></div>";
                

                // Clear form for new entry
                $sku = $name = $generic_name = $unit = $category = '';
                $vat_percent = $buying_price = $selling_price = 0;
                
            } catch (PDOException $e) {
                $message = "<div class='alert alert-danger'>Error adding product: " . htmlspecialchars($e->getMessage()) . "</div>";
            }
        }
    }
}

// Get existing categories and units from database for suggestions
$existing_categories = $pdo->query("SELECT DISTINCT category FROM products WHERE category IS NOT NULL AND category != '' ORDER BY category")->fetchAll(PDO::FETCH_COLUMN);
$existing_units = $pdo->query("SELECT DISTINCT unit FROM products WHERE unit IS NOT NULL AND unit != '' ORDER BY unit")->fetchAll(PDO::FETCH_COLUMN);

// Define lists of standard units and categories
$standard_units = [
    'tablet', 'capsule', 'caplet', 'pill', 'lozenge', 'chewable', 'effervescent', 'sublingual',
    'syrup', 'suspension', 'elixir', 'solution', 'drops', 'emulsion', 'liniment', 'mouthwash',
    'cream', 'ointment', 'gel', 'lotion', 'paste', 'spray', 'powder', 'patch',
    'injection', 'ampoule', 'vial', 'infusion', 'prefilled syringe',
    'bottle', 'pack', 'box', 'blister', 'strip', 'sachet', 'tube', 'jar', 'can',
    'suppository', 'inhaler', 'nebulizer', 'eye drops', 'ear drops', 'nasal spray', 'implant'
];

$standard_categories = [
    'Analgesic', 'Anti-inflammatory', 'Antipyretic', 'Antibiotic', 'Antiviral', 'Antifungal',
    'Antiparasitic', 'Antimalarial', 'Antacid', 'Antiulcer', 'Laxative', 'Antidiarrheal',
    'Antiemetic', 'Antihypertensive', 'Antidiabetic', 'Antiasthmatic', 'Bronchodilator',
    'Anticoagulant', 'Diuretic', 'Antidepressant', 'Antipsychotic', 'Anxiolytic',
    'Antiepileptic', 'Thyroid', 'Cholesterol', 'Cough & Cold', 'Allergy', 'Decongestant',
    'Expectorant', 'Antitussive', 'Muscle Relaxant', 'Antihistamine', 'Dermatological',
    'Antiseptic', 'Disinfectant', 'Wound Care', 'Burn Treatment', 'Anti-itch',
    'Acne Treatment', 'Antifungal Cream', 'Contraceptive', 'Hormone Therapy', 'Fertility',
    'Pregnancy', 'Menopause', 'Erectile Dysfunction', 'Prostate', 'Hair Loss', 'Vitamin',
    'Mineral', 'Multivitamin', 'Probiotic', 'Protein', 'Amino Acid', 'Herbal',
    'Sports Nutrition', 'First Aid', 'Bandage', 'Medical Device', 'Diagnostic',
    'Surgical', 'Injection Supplies', 'Ophthalmic', 'Otic', 'Dental', 'Veterinary',
    'Pediatric', 'Geriatric', 'Palliative Care'
];
?>

<style>
/* Add product page specific styles */
.main-content-wrapper {
    padding: 20px;
    min-height: calc(100vh - 80px);
    background-color: #f5f7fb;
}

.card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    transition: transform 0.2s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0,0,0,0.12);
}

.form-control {
    border-radius: 8px;
    padding: 10px 12px;
    border: 1px solid #ddd;
    transition: border 0.3s ease;
}

.form-control:focus {
    border-color: #4c1d95;
    box-shadow: 0 0 0 0.2rem rgba(76, 29, 149, 0.25);
}

.alert {
    border-radius: 10px;
    border: none;
}

.btn-success {
    background: linear-gradient(135deg, #28a745, #20c997);
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}

.btn-secondary {
    background: linear-gradient(135deg, #6c757d, #495057);
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.btn-secondary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .main-content-wrapper {
        padding: 15px 10px;
    }
    
    .card {
        margin-bottom: 15px;
    }
    
    .row {
        margin-left: -5px;
        margin-right: -5px;
    }
    
    .col-md-6 {
        padding-left: 5px;
        padding-right: 5px;
    }
}

/* Custom dropdown styles */
select option {
    padding: 8px;
}

/* Category and Unit badge styles */
.existing-items {
    margin-top: 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.existing-badge {
    font-size: 0.8rem;
    padding: 3px 8px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.existing-badge:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

/* Price calculation info */
.price-info {
    font-size: 0.85rem;
    color: #6c757d;
    margin-top: 5px;
}

.profit-badge {
    font-size: 0.8rem;
    padding: 2px 6px;
    border-radius: 4px;
}
</style>

<!-- MAIN CONTENT WRAPPER - This will shift when sidebar collapses -->
<div class="main-content-wrapper" id="mainContent">
    <div class="container-fluid">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="card p-4">
                    <h3 class="text-success mb-4">
                        <i class="fas fa-plus-circle"></i> Add New Product
                    </h3>

                    <?php echo $message; ?>

                    <form method="POST" action="" id="productForm">
                        <div class="form-group mb-3">
                            <label>SKU (leave empty to auto-generate)</label>
                            <input type="text" name="sku" class="form-control" placeholder="Leave blank for auto-generation" 
                                   value="<?php echo htmlspecialchars($sku); ?>">
                            <small class="text-muted">Unique identifier for the product</small>
                        </div>
                        
                        <div class="form-group mb-3">
                            <label>Product Name *</label>
                            <input type="text" name="name" class="form-control" required 
                                   value="<?php echo htmlspecialchars($name); ?>" placeholder="e.g., Paracetamol 500mg">
                        </div>
                        
                        <div class="form-group mb-3">
                            <label>Generic Name</label>
                            <input type="text" name="generic_name" class="form-control" 
                                   value="<?php echo htmlspecialchars($generic_name); ?>" placeholder="e.g., Acetaminophen">
                            <small class="text-muted">Active pharmaceutical ingredient</small>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label>Unit</label>
                                    <select name="unit" class="form-control" id="unitSelect">
                                        <option value="">-- Select or Custom --</option>
                                        
                                        <!-- Solid Forms -->
                                        <optgroup label="Solid Forms">
                                            <option value="tablet" <?php echo ($unit == 'tablet') ? 'selected' : ''; ?>>Tablet</option>
                                            <option value="capsule" <?php echo ($unit == 'capsule') ? 'selected' : ''; ?>>Capsule</option>
                                            <option value="caplet" <?php echo ($unit == 'caplet') ? 'selected' : ''; ?>>Caplet</option>
                                            <option value="pill" <?php echo ($unit == 'pill') ? 'selected' : ''; ?>>Pill</option>
                                            <option value="lozenge" <?php echo ($unit == 'lozenge') ? 'selected' : ''; ?>>Lozenge</option>
                                            <option value="chewable" <?php echo ($unit == 'chewable') ? 'selected' : ''; ?>>Chewable Tablet</option>
                                            <option value="effervescent" <?php echo ($unit == 'effervescent') ? 'selected' : ''; ?>>Effervescent Tablet</option>
                                            <option value="sublingual" <?php echo ($unit == 'sublingual') ? 'selected' : ''; ?>>Sublingual Tablet</option>
                                        </optgroup>
                                        
                                        <!-- Liquid Forms -->
                                        <optgroup label="Liquid Forms">
                                            <option value="syrup" <?php echo ($unit == 'syrup') ? 'selected' : ''; ?>>Syrup</option>
                                            <option value="suspension" <?php echo ($unit == 'suspension') ? 'selected' : ''; ?>>Suspension</option>
                                            <option value="elixir" <?php echo ($unit == 'elixir') ? 'selected' : ''; ?>>Elixir</option>
                                            <option value="solution" <?php echo ($unit == 'solution') ? 'selected' : ''; ?>>Solution</option>
                                            <option value="drops" <?php echo ($unit == 'drops') ? 'selected' : ''; ?>>Drops</option>
                                            <option value="emulsion" <?php echo ($unit == 'emulsion') ? 'selected' : ''; ?>>Emulsion</option>
                                            <option value="liniment" <?php echo ($unit == 'liniment') ? 'selected' : ''; ?>>Liniment</option>
                                            <option value="mouthwash" <?php echo ($unit == 'mouthwash') ? 'selected' : ''; ?>>Mouthwash</option>
                                        </optgroup>
                                        
                                        <!-- Topical Forms -->
                                        <optgroup label="Topical Forms">
                                            <option value="cream" <?php echo ($unit == 'cream') ? 'selected' : ''; ?>>Cream</option>
                                            <option value="ointment" <?php echo ($unit == 'ointment') ? 'selected' : ''; ?>>Ointment</option>
                                            <option value="gel" <?php echo ($unit == 'gel') ? 'selected' : ''; ?>>Gel</option>
                                            <option value="lotion" <?php echo ($unit == 'lotion') ? 'selected' : ''; ?>>Lotion</option>
                                            <option value="paste" <?php echo ($unit == 'paste') ? 'selected' : ''; ?>>Paste</option>
                                            <option value="spray" <?php echo ($unit == 'spray') ? 'selected' : ''; ?>>Spray</option>
                                            <option value="powder" <?php echo ($unit == 'powder') ? 'selected' : ''; ?>>Powder</option>
                                            <option value="patch" <?php echo ($unit == 'patch') ? 'selected' : ''; ?>>Patch</option>
                                        </optgroup>
                                        
                                        <!-- Parenteral Forms -->
                                        <optgroup label="Parenteral Forms">
                                            <option value="injection" <?php echo ($unit == 'injection') ? 'selected' : ''; ?>>Injection</option>
                                            <option value="ampoule" <?php echo ($unit == 'ampoule') ? 'selected' : ''; ?>>Ampoule</option>
                                            <option value="vial" <?php echo ($unit == 'vial') ? 'selected' : ''; ?>>Vial</option>
                                            <option value="infusion" <?php echo ($unit == 'infusion') ? 'selected' : ''; ?>>Infusion</option>
                                            <option value="prefilled syringe" <?php echo ($unit == 'prefilled syringe') ? 'selected' : ''; ?>>Prefilled Syringe</option>
                                        </optgroup>
                                        
                                        <!-- Packaging -->
                                        <optgroup label="Packaging">
                                            <option value="bottle" <?php echo ($unit == 'bottle') ? 'selected' : ''; ?>>Bottle</option>
                                            <option value="pack" <?php echo ($unit == 'pack') ? 'selected' : ''; ?>>Pack</option>
                                            <option value="box" <?php echo ($unit == 'box') ? 'selected' : ''; ?>>Box</option>
                                            <option value="blister" <?php echo ($unit == 'blister') ? 'selected' : ''; ?>>Blister Pack</option>
                                            <option value="strip" <?php echo ($unit == 'strip') ? 'selected' : ''; ?>>Strip</option>
                                            <option value="sachet" <?php echo ($unit == 'sachet') ? 'selected' : ''; ?>>Sachet</option>
                                            <option value="tube" <?php echo ($unit == 'tube') ? 'selected' : ''; ?>>Tube</option>
                                            <option value="jar" <?php echo ($unit == 'jar') ? 'selected' : ''; ?>>Jar</option>
                                            <option value="can" <?php echo ($unit == 'can') ? 'selected' : ''; ?>>Can</option>
                                        </optgroup>
                                        
                                        <!-- Other Forms -->
                                        <optgroup label="Other Forms">
                                            <option value="suppository" <?php echo ($unit == 'suppository') ? 'selected' : ''; ?>>Suppository</option>
                                            <option value="inhaler" <?php echo ($unit == 'inhaler') ? 'selected' : ''; ?>>Inhaler</option>
                                            <option value="nebulizer" <?php echo ($unit == 'nebulizer') ? 'selected' : ''; ?>>Nebulizer</option>
                                            <option value="eye drops" <?php echo ($unit == 'eye drops') ? 'selected' : ''; ?>>Eye Drops</option>
                                            <option value="ear drops" <?php echo ($unit == 'ear drops') ? 'selected' : ''; ?>>Ear Drops</option>
                                            <option value="nasal spray" <?php echo ($unit == 'nasal spray') ? 'selected' : ''; ?>>Nasal Spray</option>
                                            <option value="implant" <?php echo ($unit == 'implant') ? 'selected' : ''; ?>>Implant</option>
                                        </optgroup>
                                    </select>
                                    
                                    <?php 
                                    // Check if unit is custom
                                    $is_custom_unit = (!empty($unit) && !in_array($unit, $standard_units));
                                    ?>
                                    <div class="mt-2" id="customUnitContainer" style="display: <?php echo $is_custom_unit ? 'block' : 'none'; ?>;">
                                        <label>Custom Unit</label>
                                        <input type="text" name="custom_unit" class="form-control" placeholder="Enter custom unit" 
                                               value="<?php echo $is_custom_unit ? htmlspecialchars($unit) : ''; ?>">
                                    </div>
                                    
                                    <!-- Existing units from database -->
                                    <?php if (!empty($existing_units)): ?>
                                    <div class="existing-items mt-2">
                                        <small class="text-muted d-block mb-1">Existing units in your shop:</small>
                                        <?php foreach ($existing_units as $existing_unit): ?>
                                        <span class="badge badge-info existing-badge" onclick="setUnit('<?php echo htmlspecialchars($existing_unit); ?>')">
                                            <?php echo htmlspecialchars($existing_unit); ?>
                                        </span>
                                        <?php endforeach; ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label>Category</label>
                                    <select name="category" class="form-control" id="categorySelect">
                                        <option value="">-- Select or Custom --</option>
                                        
                                        <!-- Therapeutic Categories -->
                                        <optgroup label="Therapeutic Categories">
                                            <option value="Analgesic" <?php echo ($category == 'Analgesic') ? 'selected' : ''; ?>>Analgesic (Pain Reliever)</option>
                                            <option value="Anti-inflammatory" <?php echo ($category == 'Anti-inflammatory') ? 'selected' : ''; ?>>Anti-inflammatory</option>
                                            <option value="Antipyretic" <?php echo ($category == 'Antipyretic') ? 'selected' : ''; ?>>Antipyretic (Fever Reducer)</option>
                                            <option value="Antibiotic" <?php echo ($category == 'Antibiotic') ? 'selected' : ''; ?>>Antibiotic</option>
                                            <option value="Antiviral" <?php echo ($category == 'Antiviral') ? 'selected' : ''; ?>>Antiviral</option>
                                            <option value="Antifungal" <?php echo ($category == 'Antifungal') ? 'selected' : ''; ?>>Antifungal</option>
                                            <option value="Antiparasitic" <?php echo ($category == 'Antiparasitic') ? 'selected' : ''; ?>>Antiparasitic</option>
                                            <option value="Antimalarial" <?php echo ($category == 'Antimalarial') ? 'selected' : ''; ?>>Antimalarial</option>
                                            <option value="Antacid" <?php echo ($category == 'Antacid') ? 'selected' : ''; ?>>Antacid</option>
                                            <option value="Antiulcer" <?php echo ($category == 'Antiulcer') ? 'selected' : ''; ?>>Antiulcer</option>
                                            <option value="Laxative" <?php echo ($category == 'Laxative') ? 'selected' : ''; ?>>Laxative</option>
                                            <option value="Antidiarrheal" <?php echo ($category == 'Antidiarrheal') ? 'selected' : ''; ?>>Antidiarrheal</option>
                                            <option value="Antiemetic" <?php echo ($category == 'Antiemetic') ? 'selected' : ''; ?>>Antiemetic (Anti-nausea)</option>
                                        </optgroup>
                                        
                                        <!-- Chronic Conditions -->
                                        <optgroup label="Chronic Conditions">
                                            <option value="Antihypertensive" <?php echo ($category == 'Antihypertensive') ? 'selected' : ''; ?>>Antihypertensive</option>
                                            <option value="Antidiabetic" <?php echo ($category == 'Antidiabetic') ? 'selected' : ''; ?>>Antidiabetic</option>
                                            <option value="Antiasthmatic" <?php echo ($category == 'Antiasthmatic') ? 'selected' : ''; ?>>Antiasthmatic</option>
                                            <option value="Bronchodilator" <?php echo ($category == 'Bronchodilator') ? 'selected' : ''; ?>>Bronchodilator</option>
                                            <option value="Anticoagulant" <?php echo ($category == 'Anticoagulant') ? 'selected' : ''; ?>>Anticoagulant</option>
                                            <option value="Diuretic" <?php echo ($category == 'Diuretic') ? 'selected' : ''; ?>>Diuretic</option>
                                            <option value="Antidepressant" <?php echo ($category == 'Antidepressant') ? 'selected' : ''; ?>>Antidepressant</option>
                                            <option value="Antipsychotic" <?php echo ($category == 'Antipsychotic') ? 'selected' : ''; ?>>Antipsychotic</option>
                                            <option value="Anxiolytic" <?php echo ($category == 'Anxiolytic') ? 'selected' : ''; ?>>Anxiolytic (Anti-anxiety)</option>
                                            <option value="Antiepileptic" <?php echo ($category == 'Antiepileptic') ? 'selected' : ''; ?>>Antiepileptic</option>
                                            <option value="Thyroid" <?php echo ($category == 'Thyroid') ? 'selected' : ''; ?>>Thyroid Medication</option>
                                            <option value="Cholesterol" <?php echo ($category == 'Cholesterol') ? 'selected' : ''; ?>>Cholesterol Lowering</option>
                                        </optgroup>
                                        
                                        <!-- Common Conditions -->
                                        <optgroup label="Common Conditions">
                                            <option value="Cough & Cold" <?php echo ($category == 'Cough & Cold') ? 'selected' : ''; ?>>Cough & Cold</option>
                                            <option value="Allergy" <?php echo ($category == 'Allergy') ? 'selected' : ''; ?>>Allergy</option>
                                            <option value="Decongestant" <?php echo ($category == 'Decongestant') ? 'selected' : ''; ?>>Decongestant</option>
                                            <option value="Expectorant" <?php echo ($category == 'Expectorant') ? 'selected' : ''; ?>>Expectorant</option>
                                            <option value="Antitussive" <?php echo ($category == 'Antitussive') ? 'selected' : ''; ?>>Antitussive (Cough Suppressant)</option>
                                            <option value="Muscle Relaxant" <?php echo ($category == 'Muscle Relaxant') ? 'selected' : ''; ?>>Muscle Relaxant</option>
                                            <option value="Antihistamine" <?php echo ($category == 'Antihistamine') ? 'selected' : ''; ?>>Antihistamine</option>
                                        </optgroup>
                                        
                                        <!-- Topical & External -->
                                        <optgroup label="Topical & External">
                                            <option value="Dermatological" <?php echo ($category == 'Dermatological') ? 'selected' : ''; ?>>Dermatological</option>
                                            <option value="Antiseptic" <?php echo ($category == 'Antiseptic') ? 'selected' : ''; ?>>Antiseptic</option>
                                            <option value="Disinfectant" <?php echo ($category == 'Disinfectant') ? 'selected' : ''; ?>>Disinfectant</option>
                                            <option value="Wound Care" <?php echo ($category == 'Wound Care') ? 'selected' : ''; ?>>Wound Care</option>
                                            <option value="Burn Treatment" <?php echo ($category == 'Burn Treatment') ? 'selected' : ''; ?>>Burn Treatment</option>
                                            <option value="Anti-itch" <?php echo ($category == 'Anti-itch') ? 'selected' : ''; ?>>Anti-itch</option>
                                            <option value="Acne Treatment" <?php echo ($category == 'Acne Treatment') ? 'selected' : ''; ?>>Acne Treatment</option>
                                            <option value="Antifungal Cream" <?php echo ($category == 'Antifungal Cream') ? 'selected' : ''; ?>>Antifungal Cream</option>
                                        </optgroup>
                                        
                                        <!-- Women's Health -->
                                        <optgroup label="Women's Health">
                                            <option value="Contraceptive" <?php echo ($category == 'Contraceptive') ? 'selected' : ''; ?>>Contraceptive</option>
                                            <option value="Hormone Therapy" <?php echo ($category == 'Hormone Therapy') ? 'selected' : ''; ?>>Hormone Therapy</option>
                                            <option value="Fertility" <?php echo ($category == 'Fertility') ? 'selected' : ''; ?>>Fertility</option>
                                            <option value="Pregnancy" <?php echo ($category == 'Pregnancy') ? 'selected' : ''; ?>>Pregnancy & Nursing</option>
                                            <option value="Menopause" <?php echo ($category == 'Menopause') ? 'selected' : ''; ?>>Menopause</option>
                                        </optgroup>
                                        
                                        <!-- Men's Health -->
                                        <optgroup label="Men's Health">
                                            <option value="Erectile Dysfunction" <?php echo ($category == 'Erectile Dysfunction') ? 'selected' : ''; ?>>Erectile Dysfunction</option>
                                            <option value="Prostate" <?php echo ($category == 'Prostate') ? 'selected' : ''; ?>>Prostate Health</option>
                                            <option value="Hair Loss" <?php echo ($category == 'Hair Loss') ? 'selected' : ''; ?>>Hair Loss Treatment</option>
                                        </optgroup>
                                        
                                        <!-- Supplements & Nutrition -->
                                        <optgroup label="Supplements & Nutrition">
                                            <option value="Vitamin" <?php echo ($category == 'Vitamin') ? 'selected' : ''; ?>>Vitamin</option>
                                            <option value="Mineral" <?php echo ($category == 'Mineral') ? 'selected' : ''; ?>>Mineral</option>
                                            <option value="Multivitamin" <?php echo ($category == 'Multivitamin') ? 'selected' : ''; ?>>Multivitamin</option>
                                            <option value="Probiotic" <?php echo ($category == 'Probiotic') ? 'selected' : ''; ?>>Probiotic</option>
                                            <option value="Protein" <?php echo ($category == 'Protein') ? 'selected' : ''; ?>>Protein Supplement</option>
                                            <option value="Amino Acid" <?php echo ($category == 'Amino Acid') ? 'selected' : ''; ?>>Amino Acid</option>
                                            <option value="Herbal" <?php echo ($category == 'Herbal') ? 'selected' : ''; ?>>Herbal Supplement</option>
                                            <option value="Sports Nutrition" <?php echo ($category == 'Sports Nutrition') ? 'selected' : ''; ?>>Sports Nutrition</option>
                                        </optgroup>
                                        
                                        <!-- First Aid & Medical Supplies -->
                                        <optgroup label="First Aid & Medical Supplies">
                                            <option value="First Aid" <?php echo ($category == 'First Aid') ? 'selected' : ''; ?>>First Aid</option>
                                            <option value="Bandage" <?php echo ($category == 'Bandage') ? 'selected' : ''; ?>>Bandage & Dressing</option>
                                            <option value="Medical Device" <?php echo ($category == 'Medical Device') ? 'selected' : ''; ?>>Medical Device</option>
                                            <option value="Diagnostic" <?php echo ($category == 'Diagnostic') ? 'selected' : ''; ?>>Diagnostic Equipment</option>

                                            <option value="Surgical" <?php echo ($category == 'Surgical') ? 'selected' : ''; ?>>Surgical Supplies</option>
                                            <option value="Injection Supplies" <?php echo ($category == 'Injection Supplies') ? 'selected' : ''; ?>>Injection Supplies</option>
                                        </optgroup>
                                        
                                        <!-- Other Categories -->
                                        <optgroup label="Other Categories">
                                            <option value="Ophthalmic" <?php echo ($category == 'Ophthalmic') ? 'selected' : ''; ?>>Ophthalmic (Eye)</option>
                                            <option value="Otic" <?php echo ($category == 'Otic') ? 'selected' : ''; ?>>Otic (Ear)</option>
                                            <option value="Dental" <?php echo ($category == 'Dental') ? 'selected' : ''; ?>>Dental Care</option>
                                            <option value="Veterinary" <?php echo ($category == 'Veterinary') ? 'selected' : ''; ?>>Veterinary</option>
                                            <option value="Pediatric" <?php echo ($category == 'Pediatric') ? 'selected' : ''; ?>>Pediatric</option>
                                            <option value="Geriatric" <?php echo ($category == 'Geriatric') ? 'selected' : ''; ?>>Geriatric</option>
                                            <option value="Palliative Care" <?php echo ($category == 'Palliative Care') ? 'selected' : ''; ?>>Palliative Care</option>
                                        </optgroup>
                                    </select>
                                    
                                    <?php 
                                    // Check if category is custom
                                    $is_custom_category = (!empty($category) && !in_array($category, $standard_categories));
                                    ?>
                                    <div class="mt-2" id="customCategoryContainer" style="display: <?php echo $is_custom_category ? 'block' : 'none'; ?>;">
                                        <label>Custom Category</label>
                                        <input type="text" name="custom_category" class="form-control" placeholder="Enter custom category" 
                                               value="<?php echo $is_custom_category ? htmlspecialchars($category) : ''; ?>">
                                    </div>
                                    
                                    <!-- Existing categories from database -->
                                    <?php if (!empty($existing_categories)): ?>
                                    <div class="existing-items mt-2">
                                        <small class="text-muted d-block mb-1">Existing categories in your shop:</small>
                                        <?php foreach ($existing_categories as $existing_category): ?>
                                        <span class="badge badge-success existing-badge" onclick="setCategory('<?php echo htmlspecialchars($existing_category); ?>')">
                                            <?php echo htmlspecialchars($existing_category); ?>
                                        </span>
                                        <?php endforeach; ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group mb-3">
                            <label>VAT %</label>
                            <input type="number" step="0.01" min="0" max="100" name="vat_percent" class="form-control" 
                                   value="<?php echo htmlspecialchars($vat_percent); ?>">
                            <small class="text-muted">Value Added Tax percentage (0-100)</small>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label>Default Buying Price *</label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">$</span>
                                        </div>
                                        <input type="number" step="0.01" min="0" name="buying_price" class="form-control" required 
                                               value="<?php echo htmlspecialchars($buying_price); ?>" id="buyingPrice">
                                    </div>
                                    <small class="text-muted">Cost price from supplier</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label>Default Selling Price *</label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">$</span>
                                        </div>
                                        <input type="number" step="0.01" min="0" name="selling_price" class="form-control" required 
                                               value="<?php echo htmlspecialchars($selling_price); ?>" id="sellingPrice">
                                    </div>
                                    <small class="text-muted">Price to customers</small>
                                    <div id="priceInfo" class="price-info"></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="alert alert-info">
                            <small>
                                <i class="fas fa-info-circle"></i> 
                                <strong>Note:</strong> This adds the product master record. To add actual stock, 
                                you need to create a purchase order with batch details (quantity, expiry date, batch number).
                            </small>
                        </div>
                        
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-plus-circle"></i> Add Product
                            </button>
                            <a href="view_product.php" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> Back to Products
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const unitSelect = document.getElementById('unitSelect');
    const customUnitContainer = document.getElementById('customUnitContainer');
    const categorySelect = document.getElementById('categorySelect');
    const customCategoryContainer = document.getElementById('customCategoryContainer');
    const buyingPriceInput = document.getElementById('buyingPrice');
    const sellingPriceInput = document.getElementById('sellingPrice');
    const priceInfo = document.getElementById('priceInfo');
    
    // Unit handling
    unitSelect.addEventListener('change', function() {
        if (this.value === '') {
            customUnitContainer.style.display = 'block';
            customUnitContainer.querySelector('input').required = true;
        } else {
            customUnitContainer.style.display = 'none';
            customUnitContainer.querySelector('input').required = false;
            customUnitContainer.querySelector('input').value = '';
        }
    });
    
    // Category handling
    categorySelect.addEventListener('change', function() {
        if (this.value === '') {
            customCategoryContainer.style.display = 'block';
            customCategoryContainer.querySelector('input').required = true;
        } else {
            customCategoryContainer.style.display = 'none';
            customCategoryContainer.querySelector('input').required = false;
            customCategoryContainer.querySelector('input').value = '';
        }
    });
    
    // Function to set unit from existing badge
    window.setUnit = function(unit) {
        // Check if unit exists in select options
        const options = Array.from(unitSelect.options);
        const unitExists = options.some(option => option.value === unit);
        
        if (unitExists) {
            unitSelect.value = unit;
            customUnitContainer.style.display = 'none';
        } else {
            unitSelect.value = '';
            customUnitContainer.style.display = 'block';
            customUnitContainer.querySelector('input').value = unit;
        }
    };
    
    // Function to set category from existing badge
    window.setCategory = function(category) {
        // Check if category exists in select options
        const options = Array.from(categorySelect.options);
        const categoryExists = options.some(option => option.value === category);
        
        if (categoryExists) {
            categorySelect.value = category;
            customCategoryContainer.style.display = 'none';
        } else {
            categorySelect.value = '';
            customCategoryContainer.style.display = 'block';
            customCategoryContainer.querySelector('input').value = category;
        }
    };
    
    // Calculate and display price information
    function calculatePriceInfo() {
        const buyingPrice = parseFloat(buyingPriceInput.value) || 0;
        const sellingPrice = parseFloat(sellingPriceInput.value) || 0;
        
        if (buyingPrice > 0 && sellingPrice > 0) {
            const profit = sellingPrice - buyingPrice;
            const margin = (profit / buyingPrice) * 100;
            
            let infoHTML = '';
            infoHTML += `Profit: <span class="font-weight-bold ${profit >= 0 ? 'text-success' : 'text-danger'}">$${profit.toFixed(2)}</span> | `;
            infoHTML += `Margin: <span class="font-weight-bold ${margin >= 0 ? 'text-success' : 'text-danger'}">${margin.toFixed(1)}%</span>`;
            
            if (margin < 0) {
                infoHTML += ' <span class="badge badge-danger profit-badge">LOSS</span>';
            } else if (margin < 10) {
                infoHTML += ' <span class="badge badge-warning profit-badge">LOW MARGIN</span>';
            } else if (margin < 30) {
                infoHTML += ' <span class="badge badge-info profit-badge">GOOD MARGIN</span>';
            } else {
                infoHTML += ' <span class="badge badge-success profit-badge">HIGH MARGIN</span>';
            }
            
            priceInfo.innerHTML = infoHTML;
        } else {
            priceInfo.innerHTML = '';
        }
    }
    
    // Auto-calculate selling price with 30% markup
    buyingPriceInput.addEventListener('blur', function() {
        const buyingPrice = parseFloat(this.value) || 0;
        const currentSellingPrice = parseFloat(sellingPriceInput.value) || 0;
        
        // Only auto-calculate if selling price is 0 or empty and buying price > 0
        if (buyingPrice > 0 && (currentSellingPrice === 0 || isNaN(currentSellingPrice))) {
            // Default 30% markup
            const defaultMarkup = 1.3;
            sellingPriceInput.value = (buyingPrice * defaultMarkup).toFixed(2);
        }
        
        calculatePriceInfo();
    });
    
    sellingPriceInput.addEventListener('input', calculatePriceInfo);
    sellingPriceInput.addEventListener('blur', calculatePriceInfo);
    
    // Calculate on page load if both prices exist
    if (buyingPriceInput.value && sellingPriceInput.value) {
        calculatePriceInfo();
    }
    
    // Prevent duplicate form submission
    const form = document.getElementById('productForm');
    let isSubmitting = false;
    
    form.addEventListener('submit', function(e) {
        if (isSubmitting) {
            e.preventDefault();
            return false;
        }
        isSubmitting = true;
        
        // Disable submit button
        const submitBtn = form.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Adding Product...';
        
        return true;
    });
});
</script>

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