<div class="page-header">
    <div>
        <a href="<?= APP_URL ?>/products" class="btn btn-ghost btn-sm mb-4" style="padding-left:0;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>
            Back to Products
        </a>
        <h1>Add Products</h1>
    </div>
    <div class="flex gap-2">
        <button type="button" id="singleAddBtn" class="btn btn-primary active" onclick="showSingleAdd()">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
            Single Add
        </button>
        <button type="button" id="bulkImportBtn" class="btn btn-outline" onclick="showBulkImport()">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
            Bulk Import
        </button>
    </div>
</div>

<?php
// Get all units from the system
$units = Unit::all();

// Check if wholesale pricing should be shown
$showWholesale = PlanGuard::hasFeature('wholesale_pricing') || true; // Default to show if plan doesn't specify

// Check user preference or system setting for wholesale visibility
$wholesaleEnabled = false; // Default to hidden
?>

<!-- Single Add Form -->
<div id="singleAddSection">
<form action="<?= APP_URL ?>/products/create" method="POST" enctype="multipart/form-data">
    <?= Security::csrfField() ?>

    <div class="grid-2">
        <div class="card">
            <div class="card-header"><h3 class="card-title">Basic Details</h3></div>
            
            <div class="form-group">
                <label class="form-label">Product Name <span class="required">*</span></label>
                <input type="text" name="name" class="form-control" required placeholder="e.g. AirPods Pro Gen 2">
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">SKU <span class="required">*</span></label>
                    <input type="text" name="sku" class="form-control" required placeholder="APP2-001">
                </div>
                <div class="form-group">
                    <label class="form-label">Barcode</label>
                    <input type="text" name="barcode" class="form-control" placeholder="Scan or enter barcode">
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">Category</label>
                    <select name="category_id" class="form-control">
                        <option value="">Select Category...</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>"><?= e($cat['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Delivery Location <span class="required">*</span></label>
                    <select id="location_id" name="location_id" class="form-control" required>
                        <option value="">Select Location...</option>
                        <?php foreach ($locations as $l): ?>
                            <option value="<?= $l['id']; ?>" <?php echo (isset($l['is_default']) && $l['is_default']) ? 'selected' : ''; ?> data-stock="<?= $l['current_stock'] ?? 0 ?>"><?= e($l['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group" id="initial-stock-group">
                    <label class="form-label">Initial Stock Quantity</label>
                    <div class="input-group">
                        <input type="number" id="initial_stock" name="initial_stock" class="form-control" min="0" step="1" placeholder="0" value="0">
                        <span class="input-group-text">units</span>
                    </div>
                    <small class="text-muted">Set initial stock quantity for the selected location (optional)</small>
                </div>
                <div class="form-group">
                    <label class="form-label">Brand</label>
                    <select name="brand_id" class="form-control">
                        <option value="">Select Brand...</option>
                        <?php foreach ($brands as $brand): ?>
                            <option value="<?= $brand['id'] ?>"><?= e($brand['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Tracking Features</label>
                    <div class="tracking-toggles">
                        <button type="button" id="batch-tracking-toggle" class="btn btn-outline tracking-toggle" onclick="toggleBatchTracking()">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                                <path d="M19 21V5a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2z"></path>
                                <path d="M17 5v-2h3a2 2 0 0 1-2z"></path>
                            </svg>
                            <span>Batch & Expiry Tracking</span>
                        </button>
                        <button type="button" id="serial-tracking-toggle" class="btn btn-outline tracking-toggle" onclick="toggleSerialTracking()">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                                <path d="M10 6V4a2 2 0 0 0-2h3a2 2 0 0 0-2v2"></path>
                                <path d="M17 5v-2h3a2 2 0 0 1-2z"></path>
                            </svg>
                            <span>Serial Number Tracking</span>
                        </button>
                    </div>
                </div>
                
                <!-- Batch Tracking Fields (Hidden by default) -->
                <div id="batch-tracking-fields" class="tracking-fields hidden">
                    <div class="form-group">
                        <label class="form-label">Default Batch Number</label>
                        <input type="text" name="default_batch_no" class="form-control" placeholder="e.g., BATCH-001">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Default Manufacturing Date</label>
                        <input type="date" name="default_mfg_date" class="form-control">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Default Expiry Days</label>
                        <input type="number" name="default_expiry_days" class="form-control" min="0" placeholder="e.g., 365">
                        <small class="text-muted">Number of days from manufacturing date when product expires</small>
                    </div>
                </div>
                
                <!-- Serial Number Tracking Fields (Hidden by default) -->
                <div id="serial-tracking-fields" class="tracking-fields hidden">
                    <div class="form-group">
                        <label class="form-label">Serial Number Prefix</label>
                        <input type="text" name="serial_prefix" class="form-control" placeholder="e.g., SN-">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Serial Number Format</label>
                        <select name="serial_format" class="form-control">
                            <option value="sequential">Sequential (SN-001, SN-002)</option>
                            <option value="random">Random (8-digit)</option>
                            <option value="custom">Custom Pattern</option>
                        </select>
                    </div>
                </div>
                
                <input type="hidden" name="batch_tracking" id="batch_tracking_input" value="0">
                <input type="hidden" name="serial_tracking" id="serial_tracking_input" value="0">
            </div>

            <div class="form-group">
                <label class="form-label">Product Image</label>
                <input type="file" name="image" class="form-control" accept=".jpg,.jpeg,.png,.webp">
            </div>
            
            <div class="form-group">
                <label class="form-label">Description</label>
                <textarea name="description" class="form-control"></textarea>
            </div>
        </div>

        <div>
            <div class="card">
                <div class="card-header"><h3 class="card-title">Pricing & Units</h3></div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Cost Price</label>
                        <div class="input-group">
                            <span class="input-group-text"><?= setting('currency_symbol', '$') ?></span>
                            <input type="number" step="0.01" name="cost_price" class="form-control" value="0.00" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Selling Price <span class="required">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text"><?= setting('currency_symbol', '$') ?></span>
                            <input type="number" step="0.01" name="selling_price" class="form-control" value="0.00" required>
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Base Unit</label>
                        <select name="unit" class="form-control" id="unit-select">
                            <option value="">Select Unit...</option>
                            <?php foreach ($units as $unit): ?>
                                <option value="<?= $unit['name'] ?>"><?= e($unit['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-hint">Select from available units or enter custom unit</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Low Stock Alert</label>
                        <input type="number" name="alert_qty" class="form-control" value="<?= setting('low_stock_threshold', 5) ?>">
                    </div>
                </div>

                <div class="flex justify-between items-center mb-4">
                    <h4 class="text-sm text-muted">Wholesale Pricing Options</h4>
                    <button type="button" id="wholesale-toggle" class="btn btn-ghost btn-sm" onclick="toggleWholesalePricing()">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;">
                            <path d="M10 6V4a2 2 0 0 0-2h3a2 2 0 0 0-2v2"></path>
                            <path d="M17 5v-2h3a2 2 0 0 1-2z"></path>
                        </svg>
                        <span id="wholesale-toggle-text">Show Wholesale Options</span>
                    </button>
                </div>

                <div id="wholesale-section" class="hidden">
                    <hr style="border:0; border-top:1px solid var(--border); margin:20px 0;">

                    <div class="form-group">
                        <label class="form-label">Wholesale Price</label>
                        <div class="input-group">
                            <span class="input-group-text"><?= setting('currency_symbol', '$') ?></span>
                            <input type="number" step="0.01" name="wholesale_price" class="form-control" value="0.00">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Wholesale Unit</label>
                            <input type="text" name="wholesale_unit" class="form-control" placeholder="e.g. Carton">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Items per Wholesale Unit</label>
                            <input type="number" name="wholesale_qty" class="form-control" value="1">
                        </div>
                    </div>
                </div>
            </div>

            <div class="flex justify-between">
                <a href="<?= APP_URL ?>/products" class="btn btn-outline">Cancel</a>
                <button type="submit" class="btn btn-primary">Save Product</button>
            </div>
        </div>
    </div>
</div>
</form>
</div>

<!-- Bulk Import Section -->
<div id="bulkImportSection" style="display:none;">
    <div class="card">
        <div class="card-header"><h3 class="card-title">Import Products from CSV</h3></div>
        
        <div class="mb-4">
            <p class="text-muted">Upload a CSV file to import multiple products at once. The CSV should have the following columns:</p>
            <div style="background:var(--bg-surface); padding:12px; border-radius:6px; font-size:0.85rem; margin-top:8px;">
                <code>name, sku, barcode, category, brand, cost_price, selling_price, unit, alert_qty, description, initial_stock</code>
            </div>
            <p class="text-muted" style="margin-top:8px;">
                <a href="<?= APP_URL ?>/products/import-template" class="btn btn-outline btn-sm" style="display:inline-flex; align-items:center; gap:4px;">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
                    Download CSV Template
                </a>
            </p>

            <div style="margin-top:16px;">
                <h4 style="font-size:0.9rem; margin-bottom:8px; font-weight:600;">Sample CSV Format:</h4>
                <div style="background:var(--bg-surface); border:1px solid var(--border); border-radius:6px; overflow-x:auto;">
                    <table style="font-size:0.75rem; border-collapse:collapse; width:100%;">
                        <thead>
                            <tr style="background:var(--bg-raised);">
                                <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">name</th>
                                <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">sku</th>
                                <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">barcode</th>
                                <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">category</th>
                                <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">brand</th>
                                <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">cost_price</th>
                                <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">selling_price</th>
                                <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">unit</th>
                                <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">alert_qty</th>
                                <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">description</th>
                                <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">initial_stock</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">Sample Product</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">SKU-001</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">BAR-001</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">Electronics</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">Brand X</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">10.00</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">15.00</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">piece</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">5</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">Sample description</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">10</td>
                            </tr>
                            <tr>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">Another Product</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">SKU-002</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">BAR-002</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">Electronics</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">Brand Y</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">20.00</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">30.00</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">box</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">2</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">Another description</td>
                                <td style="padding:8px; border-bottom:1px solid var(--border);">5</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <form action="<?= APP_URL ?>/products/import" method="POST" enctype="multipart/form-data">
            <?= Security::csrfField() ?>

            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">CSV File <span class="required">*</span></label>
                    <input type="file" name="csv_file" class="form-control" accept=".csv" required>
                    <div class="form-hint">Max 5MB</div>
                </div>

                <div class="form-group">
                    <label class="form-label">Default Location <span class="required">*</span></label>
                    <select name="location_id" class="form-control" required>
                        <option value="">Select Location...</option>
                        <?php foreach ($locations as $l): ?>
                            <option value="<?= $l['id']; ?>"><?= e($l['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <div class="form-hint">For initial stock</div>
                </div>
            </div>

            <div class="form-group">
                <label class="flex items-center gap-2" style="cursor:pointer;">
                    <input type="checkbox" name="skip_duplicates" value="1" checked>
                    <span>Skip duplicate SKUs</span>
                </label>
                <div class="form-hint">If checked, products with existing SKUs will be skipped instead of causing errors.</div>
            </div>

            <div class="flex justify-between mt-6">
                <a href="<?= APP_URL ?>/products" class="btn btn-outline">Cancel</a>
                <button type="submit" class="btn btn-primary">Import Products</button>
            </div>
        </form>
    </div>
</div>

<style>
.hidden {
    display: none !important;
}

.tracking-toggles {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
}

.tracking-toggle {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1rem;
    border: 2px solid var(--border);
    border-radius: 8px;
    background: var(--bg);
    color: var(--text);
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.tracking-toggle:hover {
    border-color: var(--primary);
    background: var(--primary) 0.1;
}

.tracking-toggle.active {
    border-color: var(--primary);
    background: var(--primary);
    color: white;
    box-shadow: 0 2px 8px rgba(99, 102, 241, 0.2);
}

.tracking-fields {
    background: var(--bg-surface);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 1.5rem;
    margin-top: 1rem;
    transition: all 0.3s ease;
}

.tracking-fields.hidden {
    opacity: 0;
    max-height: 0;
    padding: 0 1.5rem;
    overflow: hidden;
}

.tracking-fields:not(.hidden) {
    opacity: 1;
    max-height: 500px;
    margin-top: 1rem;
}

.tracking-notification {
    position: fixed;
    top: 20px;
    right: 20px;
    background: var(--primary);
    color: white;
    padding: 1rem 1.5rem;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    z-index: 1000;
    font-weight: 500;
    transition: all 0.3s ease;
    transform: translateX(100%);
}

.tracking-notification.show {
    transform: translateX(0);
}

.tracking-notification.fade-out {
    opacity: 0;
    transform: translateX(100%);
}

.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
    align-items: start;
}

@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
        gap: 0.75rem;
    }
}
</style>

<script>
function toggleWholesalePricing() {
    const toggle = document.getElementById('wholesale-toggle');
    const wholesaleSection = document.getElementById('wholesale-section');
    const wholesaleText = document.getElementById('wholesale-toggle-text');
    
    if (wholesaleSection.classList.contains('hidden')) {
        // Show wholesale pricing
        wholesaleSection.classList.remove('hidden');
        toggle.classList.add('active');
        if (wholesaleText) wholesaleText.textContent = 'Hide Wholesale Options';
    } else {
        // Hide wholesale pricing
        wholesaleSection.classList.add('hidden');
        toggle.classList.remove('active');
        if (wholesaleText) wholesaleText.textContent = 'Show Wholesale Options';
    }
}

function toggleBatchTracking() {
    const toggle = document.getElementById('batch-tracking-toggle');
    const fields = document.getElementById('batch-tracking-fields');
    const input = document.getElementById('batch_tracking_input');
    const serialToggle = document.getElementById('serial-tracking-toggle');
    const serialFields = document.getElementById('serial-tracking-fields');
    
    if (fields.classList.contains('hidden')) {
        // Enable batch tracking
        fields.classList.remove('hidden');
        toggle.classList.add('active');
        toggle.classList.add('btn-primary');
        toggle.classList.remove('btn-outline');
        input.value = '1';
        
        // Show notification
        showTrackingNotification('Batch & Expiry Tracking enabled');
    } else {
        // Disable batch tracking
        fields.classList.add('hidden');
        toggle.classList.remove('active');
        toggle.classList.add('btn-outline');
        toggle.classList.remove('btn-primary');
        input.value = '0';
        
        // Clear batch fields
        document.querySelector('input[name="default_batch_no"]').value = '';
        document.querySelector('input[name="default_mfg_date"]').value = '';
        document.querySelector('input[name="default_expiry_days"]').value = '';
        
        // Show notification
        showTrackingNotification('Batch & Expiry Tracking disabled');
    }
}

function toggleSerialTracking() {
    const toggle = document.getElementById('serial-tracking-toggle');
    const fields = document.getElementById('serial-tracking-fields');
    const input = document.getElementById('serial_tracking_input');
    const batchToggle = document.getElementById('batch-tracking-toggle');
    const batchFields = document.getElementById('batch-tracking-fields');
    
    if (fields.classList.contains('hidden')) {
        // Enable serial tracking
        fields.classList.remove('hidden');
        toggle.classList.add('active');
        toggle.classList.add('btn-primary');
        toggle.classList.remove('btn-outline');
        input.value = '1';
        
        // Show notification
        showTrackingNotification('Serial Number Tracking enabled');
    } else {
        // Disable serial tracking
        fields.classList.add('hidden');
        toggle.classList.remove('active');
        toggle.classList.add('btn-outline');
        toggle.classList.remove('btn-primary');
        input.value = '0';
        
        // Clear serial fields
        document.querySelector('input[name="serial_prefix"]').value = '';
        document.querySelector('select[name="serial_format"]').value = 'sequential';
        
        // Show notification
        showTrackingNotification('Serial Number Tracking disabled');
    }
}

function showTrackingNotification(message) {
    // Create notification element
    const notification = document.createElement('div');
    notification.className = 'tracking-notification';
    notification.textContent = message;

    // Add to page
    document.body.appendChild(notification);

    // Auto remove after 3 seconds
    setTimeout(() => {
        notification.classList.add('fade-out');
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

function showSingleAdd() {
    document.getElementById('singleAddSection').style.display = 'block';
    document.getElementById('bulkImportSection').style.display = 'none';
    document.getElementById('singleAddBtn').classList.add('btn-primary');
    document.getElementById('singleAddBtn').classList.remove('btn-outline');
    document.getElementById('bulkImportBtn').classList.add('btn-outline');
    document.getElementById('bulkImportBtn').classList.remove('btn-primary');
}

function showBulkImport() {
    document.getElementById('singleAddSection').style.display = 'none';
    document.getElementById('bulkImportSection').style.display = 'block';
    document.getElementById('singleAddBtn').classList.add('btn-outline');
    document.getElementById('singleAddBtn').classList.remove('btn-primary');
    document.getElementById('bulkImportBtn').classList.add('btn-primary');
    document.getElementById('bulkImportBtn').classList.remove('btn-outline');
}

// Initialize form state
document.addEventListener('DOMContentLoaded', function() {
    // Set initial toggle states based on hidden inputs
    const batchEnabled = document.getElementById('batch_tracking_input').value === '1';
    const serialEnabled = document.getElementById('serial_tracking_input').value === '1';
    
    if (batchEnabled) {
        document.getElementById('batch-tracking-fields').classList.remove('hidden');
        document.getElementById('batch-tracking-toggle').classList.add('active');
    }
    
    if (serialEnabled) {
        document.getElementById('serial-tracking-fields').classList.remove('hidden');
        document.getElementById('serial-tracking-toggle').classList.add('active');
    }
    
    // Initialize wholesale section visibility
    const wholesaleSection = document.getElementById('wholesale-section');
    const wholesaleToggle = document.getElementById('wholesale-toggle');
    const wholesaleText = document.getElementById('wholesale-toggle-text');
    
    // Hide wholesale section by default
    if (wholesaleSection) {
        wholesaleSection.classList.add('hidden');
    }
    if (wholesaleToggle && wholesaleText) {
        wholesaleToggle.classList.remove('active');
        wholesaleText.textContent = 'Show Wholesale Options';
    }
});
</script>
</form>
