@extends('layouts.admin')

@section('title', 'New Product')

@section('page-title', 'New Product')

@section('breadcrumbs')
    <a href="{{ route('admin.products.index') }}" class="hover:text-primary">Products</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">New Product</span>
@endsection

@section('content')
@if(session('error'))
<div class="max-w-5xl mx-auto mb-4">
    <div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
        {{ session('error') }}
    </div>
</div>
@endif

@if($errors->any())
<div class="max-w-5xl mx-auto mb-4">
    <div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
        <ul class="list-disc list-inside">
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
</div>
@endif

<form method="POST" action="{{ route('admin.products.store') }}" enctype="multipart/form-data" class="max-w-5xl mx-auto">
    @csrf
    <div class="space-y-6">
        <!-- Product Image & Type -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900 text-gray-900">Product Image & Type</h2>
            </div>
            <div class="p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Product Image -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Product Image <span class="text-red-500">*</span>
                        </label>
                        <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:border-primary transition-colors cursor-pointer" onclick="document.getElementById('productImage').click()">
                            <div class="space-y-1 text-center">
                                <div id="imagePreview" class="hidden">
                                    <img id="imagePreviewImg" src="" alt="Preview" class="mx-auto h-32 w-32 object-cover rounded-lg">
                                </div>
                                <div id="imagePlaceholder">
                                    <span class="material-symbols-outlined text-4xl text-gray-400">cloud_upload</span>
                                    <p class="text-sm text-gray-600">Upload Image</p>
                                </div>
                                <p class="text-xs text-gray-500">JPG, PNG or WEBP format, not exceeding 5MB.</p>
                            </div>
                        </div>
                        <input type="file" id="productImage" name="image" accept="image/jpeg,image/png,image/webp" class="hidden" onchange="previewImage(this)">
                    </div>

                    <!-- Item Type -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Item Type <span class="text-red-500">*</span>
                        </label>
                        <div class="flex gap-4">
                            <label class="flex items-center gap-2 p-4 border border-gray-300 rounded-lg cursor-pointer hover:border-primary transition-colors has-[:checked]:border-primary has-[:checked]:bg-primary/5">
                                <input type="radio" name="type" value="product" checked class="text-primary focus:ring-primary">
                                <div>
                                    <span class="material-symbols-outlined text-gray-500">inventory_2</span>
                                    <span class="block text-sm font-medium text-gray-900 text-gray-900">Product</span>
                                </div>
                            </label>
                            <label class="flex items-center gap-2 p-4 border border-gray-300 rounded-lg cursor-pointer hover:border-primary transition-colors has-[:checked]:border-primary has-[:checked]:bg-primary/5">
                                <input type="radio" name="type" value="service" class="text-primary focus:ring-primary">
                                <div>
                                    <span class="material-symbols-outlined text-gray-500">handyman</span>
                                    <span class="block text-sm font-medium text-gray-900 text-gray-900">Service</span>
                                </div>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Basic Information -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900 text-gray-900">Basic Information</h2>
            </div>
            <div class="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Name -->
                <div>
                    <label for="name" class="block text-sm font-medium text-gray-700 mb-2">
                        Name <span class="text-red-500">*</span>
                    </label>
                    <input type="text" id="name" name="name" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="Enter product name">
                </div>

                <!-- Code -->
                <div>
                    <label for="code" class="block text-sm font-medium text-gray-700 mb-2">Code</label>
                    <div class="flex gap-2">
                        <input type="text" id="code" name="code" class="flex-1 h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="Product code">
                        <button type="button" onclick="generateCode()" class="px-4 h-11 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200600 transition-colors text-sm font-medium">
                            Generate
                        </button>
                    </div>
                </div>

                <!-- Category -->
                <div>
                    <label for="category_id" class="block text-sm font-medium text-gray-700 mb-2">
                        Category <span class="text-red-500">*</span>
                    </label>
                    <div class="flex gap-2">
                        <select id="category_id" name="category_id" required class="flex-1 h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                            <option value="">Select category...</option>
                            @foreach($categories as $category)
                                <option value="{{ $category->id }}" @selected(old('category_id') == $category->id)>{{ $category->name }}</option>
                            @endforeach
                        </select>
                        <a href="{{ route('admin.products.categories.index') }}" target="_blank" class="px-4 h-11 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors text-sm font-medium flex items-center gap-1">
                            <span class="material-symbols-outlined text-sm">add</span>
                            Add
                        </a>
                    </div>
                </div>

                <!-- Brand -->
                <div>
                    <label for="brand_id" class="block text-sm font-medium text-gray-700 mb-2">
                        Brand <span class="text-red-500">*</span>
                    </label>
                    <div class="flex gap-2">
                        <select id="brand_id" name="brand_id" required class="flex-1 h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                            <option value="">Select brand...</option>
                            @foreach($brands as $brand)
                                <option value="{{ $brand->id }}" @selected(old('brand_id') == $brand->id)>{{ $brand->name }}</option>
                            @endforeach
                        </select>
                        <a href="{{ route('admin.products.brands.index') }}" target="_blank" class="px-4 h-11 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors text-sm font-medium flex items-center gap-1">
                            <span class="material-symbols-outlined text-sm">add</span>
                            Add
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Pricing & Units -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900 text-gray-900">Pricing & Units</h2>
            </div>
            <div class="p-6 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- Selling Price -->
                <div>
                    <label for="selling_price" class="block text-sm font-medium text-gray-700 mb-2">
                        Selling Price <span class="text-red-500">*</span>
                    </label>
                    <input type="number" id="selling_price" name="selling_price" step="0.01" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="0.00">
                </div>

                <!-- Purchase Price -->
                <div>
                    <label for="purchase_price" class="block text-sm font-medium text-gray-700 mb-2">
                        Purchase Price <span class="text-red-500">*</span>
                    </label>
                    <input type="number" id="purchase_price" name="purchase_price" step="0.01" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="0.00">
                </div>

                <!-- Discount Type -->
                <div>
                    <label for="discount_type" class="block text-sm font-medium text-gray-700 mb-2">Discount Type</label>
                    <select id="discount_type" name="discount_type" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                        <option value="fixed">Fixed</option>
                        <option value="percentage">Percentage</option>
                    </select>
                </div>

                <!-- Discount Value -->
                <div>
                    <label for="discount_value" class="block text-sm font-medium text-gray-700 mb-2">Discount Value</label>
                    <input type="number" id="discount_value" name="discount_value" value="0" step="0.01" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                </div>

                <!-- Tax -->
                <div>
                    <label for="tax_id" class="block text-sm font-medium text-gray-700 mb-2">
                        Tax <span class="text-red-500">*</span>
                    </label>
                    <div class="flex gap-2">
                        <select id="tax_id" name="tax_id" required class="flex-1 h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" style="width: 200px;">
                            <option value="">Select tax...</option>
                            @foreach($taxes as $tax)
                                <option value="{{ $tax->id }}" @selected(old('tax_id') == $tax->id)>{{ $tax->name }} ({{ $tax->rate }}%)</option>
                            @endforeach
                        </select>
                        <button type="button" onclick="openTaxModal()" class="px-4 h-11 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors text-sm font-medium flex items-center gap-1" style="color: rgba(255, 255, 255, 1);">
                            <span class="material-symbols-outlined text-sm">add</span>
                            Add
                        </button>
                    </div>
                </div>

                <!-- Unit -->
                <div>
                    <label for="unit_id" class="block text-sm font-medium text-gray-700 mb-2">
                        Unit <span class="text-red-500">*</span>
                    </label>
                    <select id="unit_id" name="unit_id" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" style="width: 200px;">
                        <option value="">Select unit...</option>
                        @foreach($units as $unit)
                            <option value="{{ $unit->id }}" @selected(old('unit_id') == $unit->id)>{{ $unit->name }} ({{ $unit->short_name }})</option>
                        @endforeach
                    </select>
                </div>
            </div>
        </div>

        <!-- Inventory Settings -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900 text-gray-900">Inventory Settings</h2>
            </div>
            <div class="p-6 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- Stock Number -->
                <div>
                    <label for="stock" class="block text-sm font-medium text-gray-700 mb-2">
                        Stock Number
                    </label>
                    <input type="number" id="stock" name="stock" value="{{ old('stock', '') }}" min="0" step="1" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="Optional — defaults to 0">
                    <p class="mt-1 text-xs text-gray-500">Current stock quantity available</p>
                </div>

                <!-- Barcode -->
                <div>
                    <label for="barcode" class="block text-sm font-medium text-gray-700 mb-2">Barcode</label>
                    <div class="flex gap-2">
                        <input type="text" id="barcode" name="barcode" class="flex-1 h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="Enter barcode">
                        <button type="button" onclick="generateBarcode()" class="px-4 h-11 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200600 transition-colors text-sm font-medium">
                            Generate
                        </button>
                    </div>
                </div>

                <!-- Alert Quantity -->
                <div>
                    <label for="alert_quantity" class="block text-sm font-medium text-gray-700 mb-2">Alert Quantity</label>
                    <input type="number" id="alert_quantity" name="alert_quantity" value="0" min="0" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                    <p class="mt-1 text-xs text-gray-500">You will be notified when stock falls below this quantity</p>
                </div>
            </div>
        </div>

        <!-- Description -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900 text-gray-900">Product Description</h2>
            </div>
            <div class="p-6">
                <textarea id="description" name="description" rows="4" class="w-full px-4 py-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow resize-none" placeholder="Enter product description..."></textarea>
            </div>
        </div>

        <!-- Gallery Images -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900 text-gray-900">Gallery Images</h2>
            </div>
            <div class="p-6">
                <div class="flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:border-primary transition-colors cursor-pointer" onclick="document.getElementById('galleryImages').click()">
                    <div class="space-y-1 text-center">
                        <span class="material-symbols-outlined text-4xl text-gray-400">collections</span>
                        <p class="text-sm text-gray-900">Browse Images</p>
                        <p class="text-xs text-gray-700">Supported formats: PNG, JPEG, WEBP (Multiple images allowed)</p>
                    </div>
                </div>
                <input type="file" id="galleryImages" name="gallery[]" accept="image/jpeg,image/png,image/webp" multiple class="hidden">
                <div id="galleryPreview" class="grid grid-cols-4 gap-4 mt-4"></div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="flex items-center justify-end gap-3">
            <a href="{{ route('admin.products.index') }}" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50800 transition-colors">
                Cancel
            </a>
            <button type="submit" id="submitBtn" class="px-5 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-blue-600 shadow-sm transition-colors flex items-center gap-2">
                <span class="material-symbols-outlined text-lg">save</span>
                <span id="submitBtnText">Save Product</span>
            </button>
        </div>
    </div>
</form>

<!-- Category Modal -->
<div id="categoryModal" data-admin-modal class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/50 backdrop-blur-sm" onclick="closeCategoryModal()"></div>
    <div class="absolute right-0 top-0 h-full w-full max-w-md bg-white shadow-2xl transform transition-transform duration-300">
        <div class="flex flex-col h-full">
            <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900">Add New Category</h2>
                <button onclick="closeCategoryModal()" class="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="categoryForm" class="flex-1 overflow-y-auto">
                <div class="p-6 space-y-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="categoryName" name="name" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                        <textarea id="categoryDescription" name="description" rows="3" class="w-full px-4 py-3 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow resize-none"></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Image</label>
                        <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:border-primary transition-colors cursor-pointer" onclick="document.getElementById('categoryImage').click()">
                            <div class="space-y-1 text-center">
                                <div id="categoryImagePreview" class="hidden">
                                    <img id="categoryImagePreviewImg" src="" alt="Preview" class="mx-auto h-24 w-24 object-cover rounded-lg">
                                </div>
                                <div id="categoryImagePlaceholder">
                                    <span class="material-symbols-outlined text-4xl text-gray-400">cloud_upload</span>
                                    <p class="text-sm text-gray-600">Upload Image</p>
                                </div>
                            </div>
                        </div>
                        <input type="file" id="categoryImage" name="image" accept="image/jpeg,image/png,image/webp" class="hidden" onchange="previewCategoryImage(this)">
                    </div>
                </div>
                <div class="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
                    <button type="button" onclick="closeCategoryModal()" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50 transition-colors">
                        Cancel
                    </button>
                    <button type="submit" class="px-5 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-blue-600 transition-colors">
                        Save Category
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Unit Modal -->
<div id="unitModal" data-admin-modal class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/50 backdrop-blur-sm" onclick="closeUnitModal()"></div>
    <div class="absolute right-0 top-0 h-full w-full max-w-md bg-white shadow-2xl transform transition-transform duration-300">
        <div class="flex flex-col h-full">
            <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900">Add New Unit</h2>
                <button onclick="closeUnitModal()" class="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="unitForm" class="flex-1 overflow-y-auto">
                <div class="p-6 space-y-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Unit Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="unitName" name="name" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="e.g., Kilogram">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Short Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="unitShortName" name="short_name" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="e.g., kg">
                    </div>
                </div>
                <div class="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
                    <button type="button" onclick="closeUnitModal()" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50 transition-colors">
                        Cancel
                    </button>
                    <button type="submit" class="px-5 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-blue-600 transition-colors">
                        Save Unit
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Tax Modal -->
<div id="taxModal" data-admin-modal class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/50 backdrop-blur-sm" onclick="closeTaxModal()"></div>
    <div class="absolute right-0 top-0 h-full w-full max-w-md bg-white shadow-2xl transform transition-transform duration-300">
        <div class="flex flex-col h-full">
            <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900">Add New Tax Rate</h2>
                <button onclick="closeTaxModal()" class="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="taxForm" class="flex-1 overflow-y-auto">
                <div class="p-6 space-y-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Tax Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="taxName" name="name" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="e.g., VAT">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Tax Code <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="taxCode" name="code" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="e.g., VAT-20">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Rate (%) <span class="text-red-500">*</span>
                        </label>
                        <input type="number" id="taxRate" name="rate" step="0.01" min="0" max="100" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="e.g., 20.00">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Type</label>
                        <select id="taxType" name="type" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                            <option value="percentage">Percentage</option>
                            <option value="fixed">Fixed</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                        <textarea id="taxDescription" name="description" rows="3" class="w-full px-4 py-3 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow resize-none"></textarea>
                    </div>
                </div>
                <div class="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
                    <button type="button" onclick="closeTaxModal()" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50 transition-colors">
                        Cancel
                    </button>
                    <button type="submit" class="px-5 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-blue-600 transition-colors">
                        Save Tax Rate
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Brand Modal -->
<div id="brandModal" data-admin-modal class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/50 backdrop-blur-sm" onclick="closeBrandModal()"></div>
    <div class="absolute right-0 top-0 h-full w-full max-w-md bg-white shadow-2xl transform transition-transform duration-300">
        <div class="flex flex-col h-full">
            <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900">Add New Brand</h2>
                <button onclick="closeBrandModal()" class="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="brandForm" class="flex-1 overflow-y-auto">
                <div class="p-6 space-y-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="brandName" name="name" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                        <textarea id="brandDescription" name="description" rows="3" class="w-full px-4 py-3 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow resize-none"></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Image</label>
                        <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:border-primary transition-colors cursor-pointer" onclick="document.getElementById('brandImage').click()">
                            <div class="space-y-1 text-center">
                                <div id="brandImagePreview" class="hidden">
                                    <img id="brandImagePreviewImg" src="" alt="Preview" class="mx-auto h-24 w-24 object-cover rounded-lg">
                                </div>
                                <div id="brandImagePlaceholder">
                                    <span class="material-symbols-outlined text-4xl text-gray-400">cloud_upload</span>
                                    <p class="text-sm text-gray-600">Upload Image</p>
                                </div>
                            </div>
                        </div>
                        <input type="file" id="brandImage" name="image" accept="image/jpeg,image/png,image/webp" class="hidden" onchange="previewBrandImage(this)">
                    </div>
                </div>
                <div class="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
                    <button type="button" onclick="closeBrandModal()" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50 transition-colors">
                        Cancel
                    </button>
                    <button type="submit" class="px-5 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-blue-600 transition-colors">
                        Save Brand
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .select2-container--default .select2-selection--single {
        height: 44px;
        border: 1px solid #d1d5db;
        border-radius: 0.5rem;
    }
    .select2-container--default .select2-selection--single .select2-selection__rendered {
        line-height: 44px;
        padding-left: 16px;
    }
    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 42px;
    }
    .select2-container {
        color: rgba(0, 0, 0, 1);
    }
    span.select2 {
        color: rgba(0, 0, 0, 1);
    }
    .select2-container--default .select2-results__option {
        background-color: white;
    }
    .select2-container--default .select2-results__option--highlighted {
        background-color: #f3f4f6;
    }
    select#tax_id option,
    select#discount_type option {
        background-color: white;
    }
    .select2-container--default .select2-selection--single .select2-selection__rendered {
        color: rgba(0, 0, 0, 1) !important;
    }
    .select2-search__field {
        color: rgba(0, 0, 0, 1) !important;
    }
    .select2-selection__placeholder {
        color: rgba(0, 0, 0, 1) !important;
    }
    select#tax_id {
        width: 200px !important;
    }
    select#unit_id {
        width: 200px !important;
    }
</style>
@endpush

@push('scripts')
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    function previewImage(input) {
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('imagePreviewImg').src = e.target.result;
                document.getElementById('imagePreview').classList.remove('hidden');
                document.getElementById('imagePlaceholder').classList.add('hidden');
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    function generateCode() {
        // Get the selected item type
        const selectedType = document.querySelector('input[name="type"]:checked').value;
        // Set prefix based on item type: PRD for product, SRC for service
        const prefix = selectedType === 'product' ? 'PRD' : 'SRC';
        const code = prefix + '-' + Math.random().toString(36).substring(2, 8).toUpperCase();
        document.getElementById('code').value = code;
    }

    // Update submit button text based on item type
    function updateSubmitButtonText() {
        const selectedType = document.querySelector('input[name="type"]:checked').value;
        const submitBtnText = document.getElementById('submitBtnText');
        if (selectedType === 'product') {
            submitBtnText.textContent = 'Save Product';
        } else {
            submitBtnText.textContent = 'Save Service';
        }
    }

    // Listen for item type changes
    document.querySelectorAll('input[name="type"]').forEach(function(radio) {
        radio.addEventListener('change', function() {
            updateSubmitButtonText();
        });
    });

    function generateBarcode() {
        const barcode = Math.floor(1000000000000 + Math.random() * 9000000000000);
        document.getElementById('barcode').value = barcode;
    }

    // Gallery preview
    document.getElementById('galleryImages').addEventListener('change', function(e) {
        const preview = document.getElementById('galleryPreview');
        preview.innerHTML = '';
        
        Array.from(e.target.files).forEach((file, index) => {
            const reader = new FileReader();
            reader.onload = function(e) {
                const div = document.createElement('div');
                div.className = 'relative';
                div.innerHTML = `
                    <img src="${e.target.result}" alt="Gallery ${index + 1}" class="w-full h-24 object-cover rounded-lg">
                    <button type="button" onclick="this.parentElement.remove()" class="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full text-xs flex items-center justify-center hover:bg-red-600">
                        <span class="material-symbols-outlined text-sm">close</span>
                    </button>
                `;
                preview.appendChild(div);
            }
            reader.readAsDataURL(file);
        });
    });

    // Category Modal Functions
    function openCategoryModal() {
        document.getElementById('categoryModal').classList.remove('hidden');
        document.getElementById('categoryForm').reset();
        document.getElementById('categoryImagePreview').classList.add('hidden');
        document.getElementById('categoryImagePlaceholder').classList.remove('hidden');
    }

    function closeCategoryModal() {
        document.getElementById('categoryModal').classList.add('hidden');
    }

    function previewCategoryImage(input) {
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('categoryImagePreviewImg').src = e.target.result;
                document.getElementById('categoryImagePreview').classList.remove('hidden');
                document.getElementById('categoryImagePlaceholder').classList.add('hidden');
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    // Brand Modal Functions
    function openBrandModal() {
        document.getElementById('brandModal').classList.remove('hidden');
        document.getElementById('brandForm').reset();
        document.getElementById('brandImagePreview').classList.add('hidden');
        document.getElementById('brandImagePlaceholder').classList.remove('hidden');
    }

    function closeBrandModal() {
        document.getElementById('brandModal').classList.add('hidden');
    }

    function previewBrandImage(input) {
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('brandImagePreviewImg').src = e.target.result;
                document.getElementById('brandImagePreview').classList.remove('hidden');
                document.getElementById('brandImagePlaceholder').classList.add('hidden');
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    // Category Form Submit
    document.getElementById('categoryForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('_token', '{{ csrf_token() }}');

        fetch('{{ route("admin.products.categories.store") }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Add new category to regular select
                const categorySelect = document.getElementById('category_id');
                const option = document.createElement('option');
                option.value = data.category.id;
                option.textContent = data.category.name;
                option.selected = true;
                categorySelect.appendChild(option);
                closeCategoryModal();
                
                // Show success message
                alert('Category created successfully!');
            } else {
                alert('Error creating category: ' + (data.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error creating category. Please try again.');
        });
    });

    // Brand Form Submit
    document.getElementById('brandForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('_token', '{{ csrf_token() }}');

        fetch('{{ route("admin.products.brands.store") }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Add new brand to regular select
                const brandSelect = document.getElementById('brand_id');
                const option = document.createElement('option');
                option.value = data.brand.id;
                option.textContent = data.brand.name;
                option.selected = true;
                brandSelect.appendChild(option);
                closeBrandModal();
                
                // Show success message
                alert('Brand created successfully!');
            } else {
                alert('Error creating brand: ' + (data.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error creating brand. Please try again.');
        });
    });

    // Unit Modal Functions
    function openUnitModal() {
        document.getElementById('unitModal').classList.remove('hidden');
        document.getElementById('unitForm').reset();
    }

    function closeUnitModal() {
        document.getElementById('unitModal').classList.add('hidden');
    }

    // Tax Modal Functions
    function openTaxModal() {
        document.getElementById('taxModal').classList.remove('hidden');
        document.getElementById('taxForm').reset();
    }

    function closeTaxModal() {
        document.getElementById('taxModal').classList.add('hidden');
    }

    // Unit Form Submit
    document.getElementById('unitForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('_token', '{{ csrf_token() }}');

        fetch('{{ route("admin.products.units.store") }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const option = new Option(data.unit.name + ' (' + data.unit.short_name + ')', data.unit.id, true, true);
                $('#unit_id').append(option).trigger('change');
                closeUnitModal();
                alert('Unit created successfully!');
            } else {
                alert('Error creating unit: ' + (data.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error creating unit. Please try again.');
        });
    });

    // Tax Form Submit
    document.getElementById('taxForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('_token', '{{ csrf_token() }}');

        fetch('/admin/tax-rates', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Add new tax to regular select
                const taxSelect = document.getElementById('tax_id');
                const option = document.createElement('option');
                option.value = data.tax.id;
                option.textContent = data.tax.name + ' (' + data.tax.rate + '%)';
                option.selected = true;
                taxSelect.appendChild(option);
                closeTaxModal();
                alert('Tax rate created successfully!');
            } else {
                alert('Error creating tax rate: ' + (data.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error creating tax rate. Please try again.');
        });
    });

    // Main form submission with validation
    document.querySelector('form[action="{{ route("admin.products.store") }}"]').addEventListener('submit', function(e) {
        const form = this;
        const submitBtn = document.getElementById('submitBtn');
        const submitBtnText = document.getElementById('submitBtnText');
        const originalText = submitBtnText.textContent;
        
        // Basic validation
        const requiredFields = form.querySelectorAll('[required]');
        let isValid = true;
        
        requiredFields.forEach(function(field) {
            if (!field.value.trim()) {
                isValid = false;
                field.classList.add('border-red-500');
            } else {
                field.classList.remove('border-red-500');
            }
        });
        
        if (!isValid) {
            e.preventDefault();
            alert('Please fill in all required fields.');
            return false;
        }
        
        // Validate file size for product image (if provided)
        const productImage = document.getElementById('productImage');
        if (productImage.files.length > 0) {
            const fileSize = productImage.files[0].size / 1024 / 1024; // Size in MB
            if (fileSize > 5) {
                e.preventDefault();
                alert('Product image size must not exceed 5MB.');
                return false;
            }
        }
        
        // Show loading state
        submitBtn.disabled = true;
        submitBtnText.textContent = 'Saving...';
        submitBtn.classList.add('opacity-75', 'cursor-not-allowed');
        
        // Form will submit normally, but we've added validation
        // If you want AJAX submission, uncomment below and remove form action
        /*
        e.preventDefault();
        const formData = new FormData(form);
        
        fetch(form.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.location.href = data.redirect || '{{ route("admin.products.index") }}';
            } else {
                submitBtn.disabled = false;
                submitBtnText.textContent = originalText;
                submitBtn.classList.remove('opacity-75', 'cursor-not-allowed');
                alert('Error: ' + (data.message || 'Failed to save product/service'));
            }
        })
        .catch(error => {
            submitBtn.disabled = false;
            submitBtnText.textContent = originalText;
            submitBtn.classList.remove('opacity-75', 'cursor-not-allowed');
            console.error('Error:', error);
            alert('An error occurred. Please try again.');
        });
        */
    });
</script>
@endpush
@endsection




