@extends('layouts.app')
@section('title', 'New Product')

@section('styles')
<style>
.section-card { background:#fff; border:1px solid #e2e8f0; border-radius:10px; padding:1.25rem; margin-bottom:1rem; }
.section-card h6 { font-weight:700; color:#1e40af; border-bottom:2px solid #dbeafe; padding-bottom:0.5rem; margin-bottom:1rem; }
.translate-btn { cursor:pointer; }
.unit-row td { padding:0.4rem !important; }
.form-label { font-weight:500; font-size:0.85rem; }
</style>
@endsection

@section('content')
<div class="d-flex align-items-center mb-3">
    <a href="{{ route('products.index') }}" class="btn btn-sm btn-outline-secondary me-3"><i class="bi bi-arrow-left"></i></a>
    <div>
        <h4 class="mb-0 fw-bold"><i class="bi bi-plus-circle text-primary me-2"></i>New Product</h4>
        <p class="text-muted mb-0 small">Auto Code: <strong>{{ $autoCode }}</strong></p>
    </div>
</div>

@if($errors->any())
<div class="alert alert-danger alert-dismissible fade show small">
    <ul class="mb-0 ps-3">
        @foreach($errors->all() as $e)<li>{{ $e }}</li>@endforeach
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
@endif

<form method="POST" action="{{ route('products.store') }}" enctype="multipart/form-data" id="productForm">
@csrf

{{-- SECTION 1: Identification --}}
<div class="section-card">
    <h6><i class="bi bi-card-list me-1"></i> Product Identification</h6>
    <div class="row g-3">
        <div class="col-md-3">
            <label class="form-label">Product Code <span class="text-danger">*</span></label>
            <input type="text" name="product_code" class="form-control form-control-sm @error('product_code') is-invalid @enderror" value="{{ old('product_code', $autoCode) }}" required>
            @error('product_code')<div class="invalid-feedback">{{ $message }}</div>@enderror
        </div>
        <div class="col-md-3">
            <label class="form-label">SKU</label>
            <input type="text" name="sku" class="form-control form-control-sm" value="{{ old('sku') }}" placeholder="Optional SKU">
        </div>
        <div class="col-md-3">
            <label class="form-label">Primary Barcode</label>
            <div class="input-group input-group-sm">
                <input type="text" name="barcode" id="barcodeInput" class="form-control @error('barcode') is-invalid @enderror" value="{{ old('barcode') }}" placeholder="Scan or type">
                <button type="button" class="btn btn-outline-secondary" id="checkBarcodeBtn" title="Check duplicates"><i class="bi bi-upc-scan"></i></button>
            </div>
            @error('barcode')<div class="text-danger small mt-1">{{ $message }}</div>@enderror
            <div id="barcodeConflict" class="text-danger small mt-1 d-none"></div>
        </div>
        <div class="col-md-3">
            <label class="form-label">Product Type <span class="text-danger">*</span></label>
            <select name="product_type" class="form-select form-select-sm" required>
                <option value="stock"     {{ old('product_type', 'stock') == 'stock' ? 'selected' : '' }}>Stock Item</option>
                <option value="service"   {{ old('product_type') == 'service' ? 'selected' : '' }}>Service</option>
                <option value="non_stock" {{ old('product_type') == 'non_stock' ? 'selected' : '' }}>Non-Stock</option>
            </select>
        </div>
    </div>
</div>

{{-- SECTION 2: Names --}}
<div class="section-card">
    <h6><i class="bi bi-translate me-1"></i> Product Names</h6>
    <div class="row g-3">
        <div class="col-md-6">
            <label class="form-label">English Name <span class="text-danger">*</span></label>
            <input type="text" name="name_en" id="nameEn" class="form-control form-control-sm @error('name_en') is-invalid @enderror" value="{{ old('name_en') }}" required placeholder="e.g. TOMATO PASTE SAUDI 48 X 135 GM">
            @error('name_en')<div class="invalid-feedback">{{ $message }}</div>@enderror
        </div>
        <div class="col-md-6">
            <label class="form-label">Arabic Name <span class="text-danger">*</span></label>
            <div class="input-group input-group-sm">
                <input type="text" name="name_ar" id="nameAr" class="form-control @error('name_ar') is-invalid @enderror" value="{{ old('name_ar') }}" dir="rtl" placeholder="سيُملأ تلقائياً" required>
                <button type="button" class="btn btn-outline-primary translate-btn" id="translateBtn" title="Auto-translate from English"><i class="bi bi-magic"></i></button>
            </div>
            @error('name_ar')<div class="invalid-feedback">{{ $message }}</div>@enderror
            <div id="translateStatus" class="text-muted small mt-1 d-none"><i class="bi bi-hourglass-split"></i> Translating...</div>
        </div>
        <div class="col-md-4">
            <label class="form-label">Short Name (EN)</label>
            <input type="text" name="short_name_en" class="form-control form-control-sm" value="{{ old('short_name_en') }}" placeholder="Abbreviated name">
        </div>
        <div class="col-md-4">
            <label class="form-label">Short Name (AR)</label>
            <input type="text" name="short_name_ar" class="form-control form-control-sm" value="{{ old('short_name_ar') }}" dir="rtl">
        </div>
        <div class="col-md-4">
            <label class="form-label">Packing Description (EN)</label>
            <input type="text" name="packing_desc_en" class="form-control form-control-sm" value="{{ old('packing_desc_en') }}" placeholder="48 X 135 GM">
        </div>
    </div>
</div>

{{-- SECTION 3: Classification --}}
<div class="section-card">
    <h6><i class="bi bi-folder2 me-1"></i> Classification</h6>
    <div class="row g-3">
        <div class="col-md-3">
            <label class="form-label">Category <span class="text-danger">*</span></label>
            <select name="category_id" class="form-select form-select-sm" required>
                <option value="">Select Category</option>
                @foreach($categories as $cat)
                    <option value="{{ $cat->id }}" {{ old('category_id') == $cat->id ? 'selected' : '' }}>{{ $cat->name_en }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">Sub-category</label>
            <select name="subcategory_id" class="form-select form-select-sm">
                <option value="">None</option>
                @foreach($categories as $cat)
                    <option value="{{ $cat->id }}" {{ old('subcategory_id') == $cat->id ? 'selected' : '' }}>{{ $cat->name_en }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">Brand</label>
            <select name="brand_id" class="form-select form-select-sm">
                <option value="">No Brand</option>
                @foreach($brands as $brand)
                    <option value="{{ $brand->id }}" {{ old('brand_id') == $brand->id ? 'selected' : '' }}>{{ $brand->name_en }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">Default Warehouse</label>
            <select name="default_warehouse_id" class="form-select form-select-sm">
                <option value="">None</option>
                @foreach($warehouses as $wh)
                    <option value="{{ $wh->id }}" {{ old('default_warehouse_id') == $wh->id ? 'selected' : '' }}>{{ $wh->name_en }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">Pack Size</label>
            <input type="number" name="pcs_per_carton" class="form-control form-control-sm" value="{{ old('pcs_per_carton') }}" placeholder="Pcs per carton">
        </div>
        <div class="col-md-2">
            <label class="form-label">Rack No.</label>
            <input type="text" name="rack_number" class="form-control form-control-sm" value="{{ old('rack_number') }}">
        </div>
        <div class="col-md-2">
            <label class="form-label">Shelf No.</label>
            <input type="text" name="shelf_number" class="form-control form-control-sm" value="{{ old('shelf_number') }}">
        </div>
    </div>
</div>

{{-- SECTION 4: Units --}}
<div class="section-card">
    <h6><i class="bi bi-rulers me-1"></i> Units of Measure</h6>
    <div class="row g-3 mb-3">
        <div class="col-md-3">
            <label class="form-label">Base Unit <span class="text-danger">*</span></label>
            <select name="base_unit_id" class="form-select form-select-sm" required>
                <option value="">Select Base Unit</option>
                @foreach($units as $unit)
                    <option value="{{ $unit->id }}" {{ old('base_unit_id') == $unit->id ? 'selected' : '' }}>{{ $unit->code }} – {{ $unit->name_en }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">Purchase Unit</label>
            <select name="purchase_unit_id" class="form-select form-select-sm">
                <option value="">Same as Base</option>
                @foreach($units as $unit)
                    <option value="{{ $unit->id }}" {{ old('purchase_unit_id') == $unit->id ? 'selected' : '' }}>{{ $unit->code }} – {{ $unit->name_en }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">Sales Unit</label>
            <select name="sales_unit_id" class="form-select form-select-sm">
                <option value="">Same as Base</option>
                @foreach($units as $unit)
                    <option value="{{ $unit->id }}" {{ old('sales_unit_id') == $unit->id ? 'selected' : '' }}>{{ $unit->code }} – {{ $unit->name_en }}</option>
                @endforeach
            </select>
        </div>
    </div>

    <h6 class="small text-secondary">Additional Unit Conversions</h6>
    <table class="table table-sm table-bordered" id="unitsTable">
        <thead class="table-light">
            <tr>
                <th>Unit</th>
                <th>Conversion Factor</th>
                <th>Purchase Price</th>
                <th>Selling Price</th>
                <th>Wholesale Price</th>
                <th><button type="button" class="btn btn-xs btn-success" onclick="addUnitRow()"><i class="bi bi-plus"></i></button></th>
            </tr>
        </thead>
        <tbody id="unitsBody"></tbody>
    </table>
</div>

{{-- SECTION 5: Pricing & VAT --}}
<div class="section-card">
    <h6><i class="bi bi-currency-dollar me-1"></i> Pricing & VAT</h6>
    <div class="row g-3">
        <div class="col-md-2">
            <label class="form-label">VAT Mode <span class="text-danger">*</span></label>
            <select name="price_mode" class="form-select form-select-sm" required>
                <option value="Exclusive VAT" {{ old('price_mode','Exclusive VAT') == 'Exclusive VAT' ? 'selected' : '' }}>Exclusive VAT</option>
                <option value="Inclusive VAT" {{ old('price_mode') == 'Inclusive VAT' ? 'selected' : '' }}>Inclusive VAT</option>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">VAT Applicable <span class="text-danger">*</span></label>
            <select name="vat_applicable" class="form-select form-select-sm" id="vatApplicable" required>
                <option value="1" {{ old('vat_applicable', '1') == '1' ? 'selected' : '' }}>Yes</option>
                <option value="0" {{ old('vat_applicable') == '0' ? 'selected' : '' }}>No (Exempt)</option>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">VAT Rate % <span class="text-danger">*</span></label>
            <select name="vat_rate" class="form-select form-select-sm" id="vatRate" required>
                <option value="15" {{ old('vat_rate', '15') == '15' ? 'selected' : '' }}>15%</option>
                <option value="0"  {{ old('vat_rate') == '0' ? 'selected' : '' }}>0%</option>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">Cost / Purchase Price <span class="text-danger">*</span></label>
            <input type="number" name="cost_price" class="form-control form-control-sm" value="{{ old('cost_price', '0.00') }}" step="0.01" min="0" required>
        </div>
        <div class="col-md-2">
            <label class="form-label">Selling Price <span class="text-danger">*</span></label>
            <input type="number" name="sale_price" class="form-control form-control-sm" value="{{ old('sale_price', '0.00') }}" step="0.01" min="0" required>
        </div>
        <div class="col-md-2">
            <label class="form-label">Wholesale Price</label>
            <input type="number" name="wholesale_price" class="form-control form-control-sm" value="{{ old('wholesale_price') }}" step="0.01" min="0">
        </div>
        <div class="col-md-2">
            <label class="form-label">Minimum Sale Price</label>
            <input type="number" name="min_sale_price" class="form-control form-control-sm" value="{{ old('min_sale_price') }}" step="0.01" min="0">
        </div>
        <div class="col-md-2">
            <label class="form-label">Retail Price</label>
            <input type="number" name="retail_price" class="form-control form-control-sm" value="{{ old('retail_price') }}" step="0.01" min="0">
        </div>
    </div>
</div>

{{-- SECTION 6: Inventory Settings --}}
<div class="section-card">
    <h6><i class="bi bi-boxes me-1"></i> Inventory Settings</h6>
    <div class="row g-3">
        <div class="col-md-2">
            <label class="form-label">Track Stock</label>
            <select name="track_stock" class="form-select form-select-sm" required>
                <option value="1" {{ old('track_stock','1') == '1' ? 'selected' : '' }}>Yes</option>
                <option value="0" {{ old('track_stock') == '0' ? 'selected' : '' }}>No</option>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">Allow Negative</label>
            <select name="allow_negative_stock" class="form-select form-select-sm" required>
                <option value="0" {{ old('allow_negative_stock','0') == '0' ? 'selected' : '' }}>No</option>
                <option value="1" {{ old('allow_negative_stock') == '1' ? 'selected' : '' }}>Yes</option>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">Min Stock Level</label>
            <input type="number" name="min_stock" class="form-control form-control-sm" value="{{ old('min_stock') }}" step="0.01" min="0">
        </div>
        <div class="col-md-2">
            <label class="form-label">Reorder Level</label>
            <input type="number" name="reorder_level" class="form-control form-control-sm" value="{{ old('reorder_level', '10') }}" step="0.01" min="0">
        </div>
        <div class="col-md-2">
            <label class="form-label">Reorder Qty</label>
            <input type="number" name="reorder_qty" class="form-control form-control-sm" value="{{ old('reorder_qty') }}" step="0.01" min="0">
        </div>
        <div class="col-md-2">
            <label class="form-label">Track Batch</label>
            <select name="track_batch" class="form-select form-select-sm" required>
                <option value="0" {{ old('track_batch','0') == '0' ? 'selected' : '' }}>No</option>
                <option value="1" {{ old('track_batch') == '1' ? 'selected' : '' }}>Yes</option>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">Track Expiry</label>
            <select name="track_expiry" class="form-select form-select-sm" required>
                <option value="0" {{ old('track_expiry','0') == '0' ? 'selected' : '' }}>No</option>
                <option value="1" {{ old('track_expiry') == '1' ? 'selected' : '' }}>Yes</option>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">Track Serial</label>
            <select name="track_serial" class="form-select form-select-sm" required>
                <option value="0" {{ old('track_serial','0') == '0' ? 'selected' : '' }}>No</option>
                <option value="1" {{ old('track_serial') == '1' ? 'selected' : '' }}>Yes</option>
            </select>
        </div>
    </div>
</div>

{{-- SECTION 7: Status & Image --}}
<div class="section-card">
    <h6><i class="bi bi-image me-1"></i> Status & Image</h6>
    <div class="row g-3">
        <div class="col-md-3">
            <label class="form-label">Status <span class="text-danger">*</span></label>
            <select name="status" class="form-select form-select-sm" required>
                <option value="active"   {{ old('status','active') == 'active'   ? 'selected' : '' }}>Active</option>
                <option value="inactive" {{ old('status') == 'inactive' ? 'selected' : '' }}>Inactive</option>
            </select>
        </div>
        <div class="col-md-4">
            <label class="form-label">Product Image</label>
            <input type="file" name="image" class="form-control form-control-sm" accept="image/*">
        </div>
        <div class="col-md-5">
            <label class="form-label">Notes</label>
            <textarea name="notes" class="form-control form-control-sm" rows="2" placeholder="Internal notes...">{{ old('notes') }}</textarea>
        </div>
    </div>
</div>

{{-- Action Buttons --}}
<div class="d-flex gap-2 justify-content-end">
    <a href="{{ route('products.index') }}" class="btn btn-outline-secondary">Cancel</a>
    <button type="submit" class="btn btn-primary px-4"><i class="bi bi-save me-1"></i>Create Product</button>
</div>

</form>
@endsection

@section('scripts')
<script>
// Auto-translate
document.getElementById('translateBtn').addEventListener('click', function() {
    const enName = document.getElementById('nameEn').value.trim();
    if (!enName) { alert('Enter English name first'); return; }

    const status = document.getElementById('translateStatus');
    status.classList.remove('d-none');

    fetch('{{ route("api.products.translate") }}', {
        method: 'POST',
        headers: {'Content-Type':'application/json','X-CSRF-TOKEN':'{{ csrf_token() }}'},
        body: JSON.stringify({text: enName})
    })
    .then(r => r.json())
    .then(data => {
        status.classList.add('d-none');
        if (data.arabic) {
            document.getElementById('nameAr').value = data.arabic;
        }
    })
    .catch(() => status.classList.add('d-none'));
});

// Barcode conflict check
document.getElementById('checkBarcodeBtn').addEventListener('click', function() {
    const barcode = document.getElementById('barcodeInput').value.trim();
    if (!barcode) return;
    const conflict = document.getElementById('barcodeConflict');
    fetch(`{{ url('/api/products/duplicate-check') }}?barcode=${encodeURIComponent(barcode)}`)
        .then(r => r.json())
        .then(data => {
            if (data.duplicates && data.duplicates.length > 0) {
                conflict.textContent = '⚠️ Barcode conflict with: ' + data.duplicates.map(d => d.name_en).join(', ');
                conflict.classList.remove('d-none');
            } else {
                conflict.textContent = '✅ Barcode is available.';
                conflict.classList.remove('d-none');
                conflict.classList.replace('text-danger', 'text-success');
            }
        });
});

// Multi-unit rows
let unitIdx = 0;
const units = @json($units->map(fn($u) => ['id' => $u->id, 'code' => $u->code, 'name_en' => $u->name_en]));

function addUnitRow() {
    const i = unitIdx++;
    const opts = units.map(u => `<option value="${u.id}">${u.code} - ${u.name_en}</option>`).join('');
    const row = `<tr class="unit-row">
        <td><select name="units[${i}][unit_id]" class="form-select form-select-sm">${opts}</select></td>
        <td><input type="number" name="units[${i}][conversion_factor]" class="form-control form-control-sm" value="1" step="0.0001" min="0.0001"></td>
        <td><input type="number" name="units[${i}][purchase_price]" class="form-control form-control-sm" step="0.01" min="0"></td>
        <td><input type="number" name="units[${i}][selling_price]" class="form-control form-control-sm" step="0.01" min="0"></td>
        <td><input type="number" name="units[${i}][wholesale_price]" class="form-control form-control-sm" step="0.01" min="0"></td>
        <td><button type="button" class="btn btn-xs btn-danger" onclick="this.closest('tr').remove()"><i class="bi bi-trash"></i></button></td>
    </tr>`;
    document.getElementById('unitsBody').insertAdjacentHTML('beforeend', row);
}

// VAT rate auto-clear when not applicable
document.getElementById('vatApplicable').addEventListener('change', function() {
    document.getElementById('vatRate').value = this.value == '0' ? '0' : '15';
});
</script>
@endsection
