@extends('layouts.app')
@section('title', isset($item) ? 'Edit Item' : 'Add Item')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="{{ route('inventory.items.index') }}">Items</a></li>
    <li class="breadcrumb-item active">{{ isset($item) ? 'Edit' : 'Add Item' }}</li>
@endsection

@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">{{ isset($item) ? 'Edit Item' : 'Add Item' }}</h1>
        @if(isset($item))<p class="page-subtitle"><code>{{ $item->code }}</code> — {{ $item->name }}</p>@endif
    </div>
    <a href="{{ route('inventory.items.index') }}" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-1"></i>Back
    </a>
</div>

{{-- Determine which tab has errors for auto-activation --}}
@php
    $tabWithError = 'tabBasic'; // default
    $accountFields = ['inventory_account_id','cogs_account_id','sales_account_id','purchase_account_id'];
    if ($errors->hasAny($accountFields)) $tabWithError = 'tabAccounts';
@endphp

<form method="POST"
      action="{{ isset($item) ? route('inventory.items.update', $item) : route('inventory.items.store') }}"
      id="itemForm">
@csrf
@if(isset($item)) @method('PUT') @endif

{{-- Scrollable tabs for mobile --}}
<div style="overflow-x:auto;-webkit-overflow-scrolling:touch;border-bottom:2px solid #dee2e6;margin-bottom:1.5rem">
    <ul class="nav nav-tabs border-0 flex-nowrap" id="itemTabs" style="min-width:max-content">
        <li class="nav-item">
            <button class="nav-link {{ $tabWithError === 'tabBasic' ? 'active' : '' }} px-3 px-sm-4"
                    data-bs-toggle="tab" data-bs-target="#tabBasic" type="button">
                <i class="bi bi-box-seam me-1 d-none d-sm-inline"></i>Basic Info
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link {{ $tabWithError === 'tabAccounts' ? 'active' : '' }} px-3 px-sm-4"
                    data-bs-toggle="tab" data-bs-target="#tabAccounts" type="button">
                <i class="bi bi-journal me-1 d-none d-sm-inline"></i>Accounts
            </button>
        </li>
        @if(count($priceLevels) > 0)
        <li class="nav-item">
            <button class="nav-link px-3 px-sm-4"
                    data-bs-toggle="tab" data-bs-target="#tabPricing" type="button">
                <i class="bi bi-tags me-1 d-none d-sm-inline"></i>Pricing
            </button>
        </li>
        @endif
    </ul>
</div>

<div class="tab-content">

    {{-- ── Tab 1: Basic Info ──────────────────────────────────────────────── --}}
    <div class="tab-pane fade {{ $tabWithError === 'tabBasic' ? 'show active' : '' }}" id="tabBasic">
        <div class="row g-4">

            {{-- Left: Item Details --}}
            <div class="col-12 col-xl-8">
                <div class="card mb-4">
                    <div class="card-header fw-semibold">
                        <i class="bi bi-info-circle me-2 text-primary"></i>Item Details
                    </div>
                    <div class="card-body">
                        <div class="row g-3">

                            <div class="col-12">
                                <label class="form-label fw-semibold">Item Name <span class="text-danger">*</span></label>
                                <input type="text" name="name" required autofocus
                                       class="form-control form-control-lg @error('name') is-invalid @enderror"
                                       value="{{ old('name', $item->name ?? '') }}"
                                       placeholder="Full item or product name">
                                @error('name')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>

                            <div class="col-12 col-sm-6">
                                <label class="form-label fw-semibold">Item Code <span class="text-danger">*</span></label>
                                <input type="text" name="code" required
                                       class="form-control @error('code') is-invalid @enderror"
                                       value="{{ old('code', $item->code ?? '') }}"
                                       placeholder="e.g. ITEM001"
                                       style="text-transform:uppercase;letter-spacing:1px;font-weight:600">
                                <div class="form-text">Unique identifier — auto-uppercased</div>
                                @error('code')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>

                            <div class="col-12 col-sm-6">
                                <label class="form-label fw-semibold">Barcode</label>
                                <div class="input-group">
                                    <span class="input-group-text text-muted"><i class="bi bi-upc"></i></span>
                                    <input type="text" name="barcode" class="form-control"
                                           value="{{ old('barcode', $item->barcode ?? '') }}"
                                           placeholder="EAN / UPC barcode">
                                </div>
                            </div>

                            <div class="col-12 col-sm-6">
                                <label class="form-label fw-semibold">Item Type <span class="text-danger">*</span></label>
                                <select name="type" id="itemType" class="form-select" required>
                                    <option value="inventory"     {{ old('type', $item->type ?? 'inventory') === 'inventory'     ? 'selected':'' }}>📦 Inventory Item</option>
                                    <option value="service"       {{ old('type', $item->type ?? '') === 'service'       ? 'selected':'' }}>⚙️ Service</option>
                                    <option value="non_inventory" {{ old('type', $item->type ?? '') === 'non_inventory' ? 'selected':'' }}>📋 Non-Inventory</option>
                                </select>
                                <div class="form-text">Controls how stock is tracked</div>
                            </div>

                            <div class="col-12 col-sm-6">
                                <label class="form-label fw-semibold">Category</label>
                                <select name="category_id" class="form-select select2 @error('category_id') is-invalid @enderror">
                                    <option value="">— No Category —</option>
                                    @foreach($categories as $cat)
                                        <option value="{{ $cat->id }}" {{ old('category_id', $item->category_id ?? '') == $cat->id ? 'selected':'' }}>
                                            {{ str_repeat('›  ', $cat->depth) }}{{ $cat->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('category_id')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>

                            <div class="col-12 col-sm-6">
                                <label class="form-label fw-semibold">Unit of Measure</label>
                                <select name="uom_id" class="form-select select2 @error('uom_id') is-invalid @enderror">
                                    <option value="">— Select UOM —</option>
                                    @foreach($uoms as $uom)
                                        <option value="{{ $uom->id }}" {{ old('uom_id', $item->uom_id ?? '') == $uom->id ? 'selected':'' }}>
                                            {{ $uom->code }} — {{ $uom->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('uom_id')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>

                            <div class="col-12 col-sm-6" id="warehouseRow">
                                <label class="form-label fw-semibold">Default Warehouse</label>
                                <select name="default_warehouse_id" class="form-select select2 @error('default_warehouse_id') is-invalid @enderror">
                                    <option value="">— Select Warehouse —</option>
                                    @foreach($warehouses as $wh)
                                        <option value="{{ $wh->id }}" {{ old('default_warehouse_id', $item->default_warehouse_id ?? '') == $wh->id ? 'selected':'' }}>
                                            {{ str_repeat('›  ', $wh->depth) }}{{ $wh->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('default_warehouse_id')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>

                            <div class="col-12 col-sm-6">
                                <label class="form-label fw-semibold">Parent Item</label>
                                <select name="parent_id" class="form-select select2">
                                    <option value="">&#8212; No Parent (Top Level) &#8212;</option>
                                    @foreach(\App\Models\Item::withoutGlobalScopes()->where('company_id',auth()->user()->company_id)->whereNull('deleted_at')->where('is_active',true)->orderBy('name')->get(['id','code','name']) as $pi)
                                        <option value="{{ $pi->id }}" {{ old('parent_id',$item->parent_id??'')==$pi->id?'selected':'' }}>
                                            {{ $pi->code?'['.$pi->code.'] ':'' }}{{ $pi->name }}
                                        </option>
                                    @endforeach
                                </select>
                                <div class="form-text">Optional &#8212; group this under a parent item</div>
                            </div>

                            <div class="col-12 col-sm-6">
                                <label class="form-label fw-semibold">Description</label>
                                <textarea name="description" class="form-control" rows="2"
                                          placeholder="Optional item description or notes">{{ old('description', $item->description ?? '') }}</textarea>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {{-- Right: Settings + Flags --}}
            <div class="col-12 col-xl-4">

                {{-- Inventory Settings --}}
                <div class="card mb-4" id="inventoryCard">
                    <div class="card-header fw-semibold">
                        <i class="bi bi-boxes me-2 text-primary"></i>Inventory Settings
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-12">
                                <label class="form-label fw-semibold">Valuation Method</label>
                                <select name="valuation_method" class="form-select">
                                    <option value="weighted_average" {{ old('valuation_method', $item->valuation_method ?? 'weighted_average') === 'weighted_average' ? 'selected':'' }}>
                                        Weighted Average
                                    </option>
                                    <option value="fifo" {{ old('valuation_method', $item->valuation_method ?? '') === 'fifo' ? 'selected':'' }}>
                                        FIFO
                                    </option>
                                </select>
                            </div>
                            <div class="col-12">
                                <label class="form-label fw-semibold">Serial / Lot Tracking</label>
                                <select name="tracking_type" class="form-select">
                                    <option value="none"   {{ old('tracking_type', $item->tracking_type ?? 'none') === 'none'   ? 'selected':'' }}>No Tracking</option>
                                    <option value="serial" {{ old('tracking_type', $item->tracking_type ?? '') === 'serial' ? 'selected':'' }}>Serial Number</option>
                                    <option value="lot"    {{ old('tracking_type', $item->tracking_type ?? '') === 'lot'    ? 'selected':'' }}>Lot / Batch</option>
                                    <option value="both"   {{ old('tracking_type', $item->tracking_type ?? '') === 'both'   ? 'selected':'' }}>Serial + Lot</option>
                                </select>
                                <div class="form-text">Controls entry in transactions</div>
                            </div>
                            <div class="col-12 col-sm-6 col-xl-12">
                                <label class="form-label fw-semibold">Reorder Level</label>
                                <div class="input-group">
                                    <input type="number" name="reorder_level" class="form-control text-end"
                                           value="{{ old('reorder_level', $item->reorder_level ?? 0) }}"
                                           min="0" step="0.0001" placeholder="0">
                                    <span class="input-group-text text-muted" style="font-size:12px">Units</span>
                                </div>
                            </div>
                            <div class="col-12 col-sm-6 col-xl-12">
                                <label class="form-label fw-semibold">Opening Stock</label>
                                <div class="input-group">
                                    <input type="number" name="opening_stock" class="form-control text-end"
                                           value="{{ old('opening_stock', $item->opening_stock ?? 0) }}"
                                           min="0" step="0.0001" placeholder="0">
                                    <span class="input-group-text text-muted" style="font-size:12px">Units</span>
                                </div>
                                <div class="form-text">For initial setup only</div>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Item Flags --}}
                <div class="card mb-4">
                    <div class="card-header fw-semibold">
                        <i class="bi bi-toggles me-2 text-primary"></i>Item Flags
                    </div>
                    <div class="card-body">
                        <div class="row g-2">
                            <div class="col-12">
                                <div class="p-3 rounded-2 border" style="background:#f8f9fa">
                                    <div class="form-check form-switch mb-0">
                                        <input class="form-check-input" type="checkbox" name="is_sold" value="1"
                                               id="isSold" {{ old('is_sold', $item->is_sold ?? true) ? 'checked':'' }}>
                                        <label class="form-check-label fw-semibold" for="isSold">
                                            Sold to Customers
                                        </label>
                                        <div class="text-muted" style="font-size:12px">Appears on sales documents</div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="p-3 rounded-2 border" style="background:#f8f9fa">
                                    <div class="form-check form-switch mb-0">
                                        <input class="form-check-input" type="checkbox" name="is_purchased" value="1"
                                               id="isPurchased" {{ old('is_purchased', $item->is_purchased ?? true) ? 'checked':'' }}>
                                        <label class="form-check-label fw-semibold" for="isPurchased">
                                            Purchased from Vendors
                                        </label>
                                        <div class="text-muted" style="font-size:12px">Appears on purchase documents</div>
                                    </div>
                                </div>
                            </div>
                            @if(isset($item))
                            <div class="col-12">
                                <div class="p-3 rounded-2 border" style="background:#f8f9fa">
                                    <div class="form-check form-switch mb-0">
                                        <input class="form-check-input" type="checkbox" name="is_active" value="1"
                                               id="isActive" {{ old('is_active', $item->is_active) ? 'checked':'' }}>
                                        <label class="form-check-label fw-semibold" for="isActive">Active</label>
                                        <div class="text-muted" style="font-size:12px">Inactive items cannot be used in new transactions</div>
                                    </div>
                                </div>
                            </div>
                            @endif
                        </div>
                    </div>
                </div>

                <div class="d-flex gap-2">
                    <a href="{{ route('inventory.items.index') }}" class="btn btn-outline-secondary flex-fill">Cancel</a>
                    <button type="submit" class="btn btn-primary flex-fill" id="saveBtn">
                        <i class="bi bi-check-circle me-1"></i>{{ isset($item) ? 'Save Changes' : 'Create Item' }}
                    </button>
                </div>
            </div>
        </div>
    </div>

    {{-- ── Tab 2: Accounts ────────────────────────────────────────────────── --}}
    <div class="tab-pane fade {{ $tabWithError === 'tabAccounts' ? 'show active' : '' }}" id="tabAccounts">
        <div class="row justify-content-center">
        <div class="col-12 col-xl-8">
        <div class="card">
            <div class="card-header fw-semibold">
                <i class="bi bi-journal-bookmark me-2 text-primary"></i>GL Account Mappings
            </div>
            <div class="card-body">
                <div class="alert alert-info d-flex gap-2 py-2 mb-4" style="font-size:13px">
                    <i class="bi bi-info-circle flex-shrink-0 mt-1"></i>
                    <div>These accounts are used when posting transactions. Leave blank to use the company default accounts configured in Settings.</div>
                </div>
                <div class="row g-4">
                    @foreach([
                        ['inventory_account_id', 'Inventory Account',      'asset',   'Stock value debit/credit (inventory items only)'],
                        ['cogs_account_id',       'Cost of Goods Sold',     'expense', 'Debited when item is sold (inventory items)'],
                        ['sales_account_id',      'Sales Revenue Account',  'income',  'Credited when item is sold'],
                        ['purchase_account_id',   'Purchase/Expense Account','expense','Used when purchasing (service/non-inventory items)'],
                    ] as [$field, $label, $type, $hint])
                    <div class="col-12 col-sm-6">
                        <label class="form-label fw-semibold">{{ $label }}</label>
                        <select name="{{ $field }}" class="form-select select2 @error($field) is-invalid @enderror">
                            <option value="">— Company Default —</option>
                            @foreach($accounts->where('type', $type) as $acc)
                                <option value="{{ $acc->id }}" {{ old($field, isset($item) ? $item->$field : '') == $acc->id ? 'selected':'' }}>
                                    {{ $acc->code ? "[{$acc->code}] " : "" }}{{ $acc->name }}
                                </option>
                            @endforeach
                        </select>
                        <div class="form-text">{{ $hint }}</div>
                        @error($field)<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                    @endforeach
                </div>
                <div class="d-flex gap-2 justify-content-end mt-4 pt-3 border-top">
                    <a href="{{ route('inventory.items.index') }}" class="btn btn-outline-secondary">Cancel</a>
                    <button type="submit" class="btn btn-primary px-4">
                        <i class="bi bi-check-circle me-1"></i>{{ isset($item) ? 'Save Changes' : 'Create Item' }}
                    </button>
                </div>
            </div>
        </div>
        </div>
        </div>
    </div>

    {{-- ── Tab 3: Pricing ─────────────────────────────────────────────────── --}}
    @if(count($priceLevels) > 0)
    <div class="tab-pane fade" id="tabPricing">
        <div class="card">
            <div class="card-header fw-semibold d-flex justify-content-between align-items-center flex-wrap gap-2">
                <span><i class="bi bi-tags me-2 text-primary"></i>Price List by Level</span>
                <span class="text-muted" style="font-size:12px">Leave blank to not set a price for that level</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0" style="min-width:500px">
                        <thead class="table-light">
                            <tr>
                                <th>Price Level</th>
                                <th class="d-none d-sm-table-cell" style="width:150px">Currency</th>
                                <th style="width:160px">Unit Price</th>
                                <th class="d-none d-md-table-cell" style="width:150px">Effective From</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($priceLevels as $pl)
                            @php $existing = isset($priceLevelData) ? $priceLevelData->get($pl->id) : null; @endphp
                            <tr>
                                <td>
                                    <div class="fw-semibold" style="font-size:13.5px">{{ $pl->name }}</div>
                                    @if($pl->is_default)
                                        <span class="badge" style="background:#d1e7dd;color:#0a3622;font-size:10px">Default</span>
                                    @endif
                                </td>
                                <td class="d-none d-sm-table-cell">
                                    <select name="price_levels[{{ $pl->id }}][currency_id]" class="form-select form-select-sm">
                                        <option value="">Base Currency</option>
                                        @foreach($currencies as $cur)
                                            <option value="{{ $cur->id }}"
                                                {{ old("price_levels.{$pl->id}.currency_id", $existing?->currency_id) == $cur->id ? 'selected':'' }}>
                                                {{ $cur->code }}
                                            </option>
                                        @endforeach
                                    </select>
                                </td>
                                <td>
                                    <input type="number"
                                           name="price_levels[{{ $pl->id }}][unit_price]"
                                           class="form-control form-control-sm text-end"
                                           value="{{ old("price_levels.{$pl->id}.unit_price", $existing ? number_format((float)$existing->unit_price, 4, '.', '') : '') }}"
                                           step="0.0001" min="0" placeholder="0.0000">
                                </td>
                                <td class="d-none d-md-table-cell">
                                    <input type="date"
                                           name="price_levels[{{ $pl->id }}][effective_date]"
                                           class="form-control form-control-sm"
                                           value="{{ old("price_levels.{$pl->id}.effective_date", $existing?->effective_date?->format('Y-m-d') ?? '') }}">
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer bg-white d-flex justify-content-end gap-2">
                <a href="{{ route('inventory.items.index') }}" class="btn btn-outline-secondary">Cancel</a>
                <button type="submit" class="btn btn-primary px-4">
                    <i class="bi bi-check-circle me-1"></i>{{ isset($item) ? 'Save Changes' : 'Create Item' }}
                </button>
            </div>
        </div>
    </div>
    @endif

</div>{{-- end tab-content --}}
</form>
@endsection

@push('scripts')
<script>
// Show/hide inventory-specific fields
function updateTypeVisibility() {
    const type        = document.getElementById('itemType').value;
    const isInventory = type === 'inventory';
    document.getElementById('inventoryCard').style.display = isInventory ? '' : 'none';
    const whRow = document.getElementById('warehouseRow');
    if (whRow) whRow.style.display = isInventory ? '' : 'none';
}
document.getElementById('itemType').addEventListener('change', updateTypeVisibility);
updateTypeVisibility();

// Auto-uppercase item code
document.querySelector('input[name="code"]')?.addEventListener('input', function() {
    const pos = this.selectionStart;
    this.value = this.value.toUpperCase().replace(/[^A-Z0-9\-_\.]/g, '');
    this.setSelectionRange(pos, pos);
});

// Submit spinner
document.getElementById('itemForm').addEventListener('submit', function() {
    const b = document.getElementById('saveBtn');
    if (b) { b.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving...'; b.disabled = true; }
});
</script>
@endpush
