<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Item Type Management</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        :root {
            --primary-color: #018ca3;
            --secondary-color: #f8f9fa;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --border-color: #dee2e6;
        }
        
        body {
            background-color: #f5f7fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding-top: 50px;
        }
        
        .container {
            max-width: 1200px;
            margin-bottom: 2rem;
        }
        
        .card {
            border-radius: 0.75rem;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
            border: none;
        }
        
        .card-header {
            background-color: var(--primary-color);
            color: white;
            border-radius: 0.75rem 0.75rem 0 0 !important;
            padding: 1.25rem;
            font-weight: 600;
            font-size: 1.25rem;
        }
        
        .card-body {
            padding: 2rem;
        }
        
        .nav-tabs-custom {
            background-color: var(--primary-color);
            border-radius: 0.5rem;
            overflow-x: auto;
            white-space: nowrap;
            padding: 0.75rem;
            margin-bottom: 1.5rem;
        }
        
        .nav-tabs-custom .nav-item {
            display: inline-block;
            margin-right: 0.5rem;
        }
        
        .nav-tabs-custom .nav-link {
            color: white;
            border: none;
            border-radius: 0.5rem;
            transition: all 0.2s ease;
            padding: 0.75rem 1.5rem;
            font-weight: 500;
        }
        
        .nav-tabs-custom .nav-link:hover:not(.active):not(.disabled) {
            background-color: rgba(255, 255, 255, 0.15);
        }
        
        .nav-tabs-custom .nav-link.active {
            background-color: white !important;
            color: var(--primary-color) !important;
            box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.1);
            border-radius: 0.5rem;
            font-weight: 600;
        }
        
        .nav-tabs-custom .nav-link.disabled {
            color: rgba(255, 255, 255, 0.6);
            cursor: not-allowed;
        }
        
        .tab-pane {
            padding: 1.5rem 0;
        }
        
        .form-header {
            font-weight: bold;
            font-size: 1.3rem;
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 0.75rem;
            margin-bottom: 1.5rem;
            color: var(--primary-color);
        }
        
        .form-label {
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: #495057;
        }
        
        .form-control, .form-select {
            border-radius: 0.5rem;
            padding: 0.75rem;
            border: 1px solid var(--border-color);
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(1, 140, 163, 0.25);
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            border-radius: 0.5rem;
            padding: 0.75rem 1.5rem;
            font-weight: 600;
            transition: all 0.2s ease;
        }
        
        .btn-primary:hover, .btn-primary:focus {
            background-color: #01748a;
            border-color: #016477;
            transform: translateY(-2px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }
        
        .btn-outline-primary {
            color: var(--primary-color);
            border-color: var(--primary-color);
            border-radius: 0.5rem;
            padding: 0.75rem 1.5rem;
            font-weight: 600;
        }
        
        .btn-outline-primary:hover {
            background-color: var(--primary-color);
            color: white;
        }
        
        .btn-group-nav {
            display: flex;
            justify-content: space-between;
            margin-top: 2rem;
            padding-top: 1.5rem;
            border-top: 1px solid var(--border-color);
        }
        
        .field-error {
            color: var(--danger-color);
            font-size: 0.875rem;
            margin-top: 0.25rem;
            font-weight: 500;
        }
        
        .image-drop-area {
            border: 2px dashed #ced4da;
            border-radius: 0.75rem;
            padding: 2rem;
            text-align: center;
            color: #6c757d;
            cursor: pointer;
            transition: all 0.2s ease;
            background-color: #f8f9fa;
        }
        
        .image-drop-area:hover, .image-drop-area.dragover {
            background-color: #e9ecef;
            border-color: var(--primary-color);
        }
        
        .image-preview {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin-top: 1rem;
        }
        
        .image-preview img {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 0.5rem;
            border: 1px solid #dee2e6;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        
        .back-link {
            color: var(--primary-color);
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            text-decoration: none;
            transition: color 0.2s ease;
            margin-bottom: 1.5rem;
        }
        
        .back-link:hover {
            color: #016477;
            text-decoration: underline;
        }
        
        .tab-indicator {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            background-color: rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            margin-right: 0.5rem;
            font-size: 0.75rem;
        }
        
        .nav-link.active .tab-indicator {
            background-color: var(--primary-color);
            color: white;
        }
        
        .progress {
            height: 8px;
            margin: 1rem 0 2rem;
            border-radius: 4px;
            background-color: #e9ecef;
        }
        
        .progress-bar {
            background-color: var(--primary-color);
            transition: width 0.4s ease;
        }
        
        .status-badge {
            position: absolute;
            top: -8px;
            right: -8px;
            background-color: var(--success-color);
            color: white;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.75rem;
            font-weight: bold;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        
        .table-section {
            background-color: white;
            border-radius: 0.75rem;
            padding: 1.5rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
            margin-bottom: 2rem;
        }
        
        .table th {
            background-color: #f8f9fa;
            color: var(--primary-color);
            font-weight: 600;
            border-top: none;
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(1, 140, 163, 0.05);
        }
        
        .hidden-tab {
            display: none !important;
        }
        
        .image-preview-item {
            position: relative;
            display: inline-block;
        }
        
        .delete-existing-image {
            position: absolute;
            top: 5px;
            right: 5px;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0;
            background: var(--danger-color);
            color: white;
            border: none;
            cursor: pointer;
        }

        /* Success/Error Messages */
        .alert-container {
            position: fixed;
            top: 150px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1050;
            width: 100%;
            max-width: 600px;
            padding: 0 15px;
        }
        
        .alert {
            opacity: 1;
            transition: opacity 0.5s ease-out;
        }
        
        .alert.fade-out {
            opacity: 0;
        }
        
        /* Edit button styling */
        .editBtn {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
        }
        
        .editBtn:hover {
            background-color: #01748a;
            border-color: #016477;
            color: white;
        }
        
        /* Navigation bar styling */
        .topbar {
            background-color: #419a40;
            display: flex;
            justify-content: center;
            align-items: center;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
            height: 70px;
        }
        
        .menu-bar {
            background-color: #018ca3;
            position: fixed;
            top: 70px;
            left: 0;
            right: 0;
            z-index: 999;
        }
        
        .topbar h3 {
            font-weight: bold;
            font-size: 1.1em;
            margin: 0;
            color: white;
        }
        
        .topbar-divider {
            height: 100%;
            border-left: 1px solid rgba(255, 255, 255, 0.3);
            margin: 0 15px;
        }
        
        .navbar-nav .nav-link {
            font-weight: bold;
            font-size: 1.3em;
            color: white;
            padding: 0.5rem 1rem;
        }
        
        .dropdown-menu {
            background-color: #018ca3;
            border: none;
            border-radius: 0.5rem;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
        }
        
        .dropdown-item {
            color: white;
            font-weight: 500;
            padding: 0.5rem 1rem;
        }
        
        .dropdown-item:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
        
        .dropdown-divider {
            border-top: 1px solid rgba(255, 255, 255, 0.3);
        }
    </style>
</head>
<body style="padding: 40px">
    <!-- Success/Error Messages -->
    <div class="alert-container">
        @if(session('success'))
            <div class="alert alert-success alert-dismissible fade show">
                {{ session('success') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif
        
        @if(session('error'))
            <div class="alert alert-danger alert-dismissible fade show">
                {{ session('error') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif
        
        @if($errors->any())
            <div class="alert alert-danger alert-dismissible fade show">
                <ul class="mb-0">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif
    </div>

    <div class="container" style="padding-bottom: 100px; padding:15px">
        <a href="{{ route('home') }}" class="back-link">
            <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
        </a>
        
        <div class="card">
            <div class="card-header">
                <i class="fas fa-cubes me-2"></i> {{ $currentRecord ? 'Edit Item Type' : 'Add New Item Type' }}
            </div>
            
            <div class="card-body" >
                <form id="itemTypeForm" action="{{ $currentRecord ? route('supplier.item_types.update', $currentRecord->id) : route('supplier.item_types.store') }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    @if($currentRecord)
                        @method('PUT')
                    @endif
                    <input type="hidden" name="deleted_images" id="deleted_images" value="">
                    
                    <!-- Progress indicator -->
                    <div class="progress">
                        <div class="progress-bar" id="formProgress" role="progressbar" style="width: 20%" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                    
                    <!-- Tabs -->
                    <ul class="nav nav-tabs nav-tabs-custom mb-4" id="itemTypeTabs" role="tablist">
                        <li class="nav-item position-relative" role="presentation">
                            <button class="nav-link active" id="tab-item" data-bs-toggle="tab" data-bs-target="#pane-item" type="button" role="tab" aria-controls="pane-item" aria-selected="true">
                                <span class="tab-indicator">1</span> Item Details
                            </button>
                        </li>
                        <li class="nav-item position-relative" role="presentation"> 
                            <button class="nav-link disabled" id="tab-info" data-bs-toggle="tab" data-bs-target="#pane-info" type="button" role="tab" aria-controls="pane-info" aria-selected="false">
                                <span class="tab-indicator">2</span> Information
                            </button>
                        </li>
                         <li class="nav-item position-relative" id="units-tab-item" role="presentation">
                            <button class="nav-link disabled" id="tab-units" data-bs-toggle="tab" data-bs-target="#pane-units" type="button" role="tab" aria-controls="pane-units" aria-selected="false">
                                <span class="tab-indicator">3</span> Units
                            </button>
                        </li>
                        <li class="nav-item position-relative" role="presentation">
                            <button class="nav-link disabled" id="tab-pricing" data-bs-toggle="tab" data-bs-target="#pane-pricing" type="button" role="tab" aria-controls="pane-pricing" aria-selected="false">
                                <span class="tab-indicator">4</span> Pricing
                            </button>
                        </li>
                        <li class="nav-item position-relative" id="warehouse-tab-item" role="presentation">
                            <button class="nav-link disabled" id="tab-warehouse" data-bs-toggle="tab" data-bs-target="#pane-warehouse" type="button" role="tab" aria-controls="pane-warehouse" aria-selected="false">
                                <span class="tab-indicator">5</span> Warehouse
                            </button>
                        </li>
                        <li class="nav-item position-relative" role="presentation">
                            <button class="nav-link disabled" id="tab-images" data-bs-toggle="tab" data-bs-target="#pane-images" type="button" role="tab" aria-controls="pane-images" aria-selected="false">
                                <span class="tab-indicator">6</span> Images
                            </button>
                        </li>
                    </ul>
                    
                    <!-- Form -->
                    <div class="tab-content">
                        <!-- Item Tab -->
                        <div class="tab-pane fade show active" id="pane-item" role="tabpanel" aria-labelledby="tab-item">
                            <div class="form-header">
                                <i class="fas fa-tag me-2"></i> Item Information
                            </div>
                            
                            <div class="row g-4">
                                <div class="col-md-6">
                                    <label for="code" class="form-label"><strong>Code <span class="text-danger">*</span></strong></label>
                                    <input type="text" class="form-control" name="code" id="code" placeholder="ITM-001" value="{{ old('code', $currentRecord->code ?? '') }}">
                                    <div class="field-error" id="error-code"></div>
                                </div>
                                
                                <div class="col-md-6">
                                    <label class="form-label"><strong>Status</strong></label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" role="switch" id="active" name="active" {{ (old('active', $currentRecord->active ?? true)) ? 'checked' : '' }}>
                                        <label class="form-check-label" for="active">Active</label>
                                    </div>
                                </div>
                                
                                <div class="col-12">
                                    <label for="description1" class="form-label"><strong>Description 1 <span class="text-danger">*</span></strong></label>
                                    <input type="text" class="form-control" name="description1" id="description1" placeholder="Main product description" value="{{ old('description1', $currentRecord->description1 ?? '') }}">
                                    <div class="field-error" id="error-description1"></div>
                                </div>
                                
                                <div class="col-12">
                                    <label for="description2" class="form-label"><strong>Description 2</strong></label>
                                    <input type="text" class="form-control" name="description2" id="description2" placeholder="Additional product details" value="{{ old('description2', $currentRecord->description2 ?? '') }}">
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="card bg-light p-3">
                                        <div class="form-check form-switch mb-2">
                                            <input class="form-check-input" type="checkbox" role="switch" id="is_service_item" name="is_service_item" {{ (old('is_service_item', $currentRecord->is_service_item ?? false)) ? 'checked' : '' }}>
                                            <label class="form-check-label" for="is_service_item">Service Item</label>
                                        </div>
                                         <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" role="switch" id="is_physical_item" name="is_physical_item" {{ (old('is_physical_item', $currentRecord->is_physical_item ?? true)) ? 'checked' : '' }}>
                                            <label class="form-check-label" for="is_physical_item">Physical Item</label>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="card bg-light p-3">
                                        <div class="form-check form-switch mb-2">
                                            <input class="form-check-input" type="checkbox" role="switch" id="has_uom" name="has_units_of_measure" {{ (old('has_units_of_measure', $currentRecord->has_units_of_measure ?? true)) ? 'checked' : '' }}>
                                            <label class="form-check-label" for="has_uom">Units of Measure</label>
                                        </div>
                                        <div class="form-check form-switch mb-2">
                                            <input class="form-check-input" type="checkbox" role="switch" id="has_warehouse" name="has_warehouse" {{ (old('has_warehouse', $currentRecord->has_warehouse ?? true)) ? 'checked' : '' }}>
                                            <label class="form-check-label" for="has_warehouse">Warehouse</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="btn-group-nav">
                                <div></div> <!-- Spacer -->
                                <button type="button" class="btn btn-primary" id="btn-item-next">
                                    Next <i class="fas fa-arrow-right ms-2"></i>
                                </button>
                            </div>
                        </div>
                        
                        <!-- Information Tab -->
                        <div class="tab-pane fade" id="pane-info" role="tabpanel" aria-labelledby="tab-info">
                            <div class="form-header">
                                <i class="fas fa-info-circle me-2"></i> Product Information
                            </div>
                            
                            <div class="row g-4">
                                <div class="col-md-6">
                                    <label for="category" class="form-label"><strong>Category <span class="text-danger">*</span></strong></label>
                                    <select class="form-select" name="category" id="category">
                                    <option value="">-- Select Category --</option>
                                    @foreach($categories as $cat)
                                        <option value="{{ $cat->id }}" 
                                            {{ old('category', $currentRecord->category_id ?? '') == $cat->id ? 'selected' : '' }}>
                                            {{ $cat->name }}
                                        </option>
                                    @endforeach
                                </select>
                                    <div class="field-error" id="error-category">
                                        @error('category') {{ $message }} @enderror
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="bin_location" class="form-label"><strong>Bin Location</strong></label>
                                    <select class="form-select" name="bin_location" id="bin_location">
                                        <option value="">-- Select Bin Location --</option>
                                        @foreach($binLocations as $bin)
                                            <option value="{{ $bin->id }}" 
                                                {{ old('bin_location', $currentRecord->bin_location_id ?? '') == $bin->id ? 'selected' : '' }}>
                                                {{ $bin->code }} @if($bin->description) - {{ $bin->description }}@endif
                                            </option>
                                        @endforeach
                                    </select>
                                    <div class="field-error" id="error-bin_location">
                                        @error('bin_location') {{ $message }} @enderror
                                    </div>
                                </div>
                                
                                <div class="col-12">
                                    <label for="barcode_box" class="form-label"><strong>Barcode</strong></label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" name="barcode_box" id="barcode_box"
                                            placeholder="Enter barcode"
                                            value="{{ old('barcode_box', $currentRecord->barcode_box ?? '') }}">
                                        <button class="btn btn-outline-secondary" type="button">
                                            <i class="fas fa-barcode"></i> Scan
                                        </button>
                                    </div>
                                    <div class="field-error" id="error-barcode_box">
                                        @error('barcode_box') {{ $message }} @enderror
                                    </div>
                                </div>
                            </div>
                            
                            <div class="btn-group-nav">
                                <button type="button" class="btn btn-outline-primary" id="btn-info-back">
                                    <i class="fas fa-arrow-left me-2"></i> Back
                                </button>
                                <button type="button" class="btn btn-primary" id="btn-info-next">
                                    Next <i class="fas fa-arrow-right ms-2"></i>
                                </button>
                            </div>
                        </div>
                        <!-- Units Tab -->
                        <div class="tab-pane fade" id="pane-units" role="tabpanel" aria-labelledby="tab-units">
                            <div class="form-header">
                                <i class="fas fa-ruler me-2"></i> Units of Measure
                            </div>
                            
                            <div class="row g-4">
                                <div class="col-md-4">
                                    <label for="stocking_unit_id" class="form-label"><strong>Stocking Unit</strong></label>
                                    <select class="form-select" name="stocking_unit_id" id="stocking_unit_id">
                                        <option value="">-- Select Stocking Unit --</option>
                                        @foreach($uoms as $uom)
                                            <option value="{{ $uom->id }}"
                                                {{ old('stocking_unit_id', $currentRecord->stocking_unit_id ?? '') == $uom->id ? 'selected' : '' }}>
                                                {{ $uom->code }}@if($uom->description) – {{ $uom->description }}@endif
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                
                                <div class="col-md-4">
                                    <label for="default_purchase_unit_id" class="form-label"><strong>Default Purchases Unit</strong></label>
                                    <select class="form-select" name="default_purchase_unit_id" id="default_purchase_unit_id">
                                        <option value="">-- Select Purchase Unit --</option>
                                        @foreach($uoms as $uom)
                                            <option value="{{ $uom->id }}"
                                                {{ old('default_purchase_unit_id', $currentRecord->default_purchase_unit_id ?? '') == $uom->id ? 'selected' : '' }}>
                                                {{ $uom->code }}@if($uom->description) – {{ $uom->description }}@endif
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                
                                <div class="col-md-4">
                                    <label for="default_sale_unit_id" class="form-label"><strong>Default Sale Unit</strong></label>
                                    <select class="form-select" name="default_sale_unit_id" id="default_sale_unit_id">
                                        <option value="">-- Select Sale Unit --</option>
                                        @foreach($uoms as $uom)
                                            <option value="{{ $uom->id }}"
                                                {{ old('default_sale_unit_id', $currentRecord->default_sale_unit_id ?? '') == $uom->id ? 'selected' : '' }}>
                                                {{ $uom->code }}@if($uom->description) – {{ $uom->description }}@endif
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            
                            <div class="btn-group-nav">
                                <button type="button" class="btn btn-outline-primary" id="btn-units-back">
                                    <i class="fas fa-arrow-left me-2"></i> Back
                                </button>
                                <button type="button" class="btn btn-primary" id="btn-units-next">
                                    Next <i class="fas fa-arrow-right ms-2"></i>
                                </button>
                            </div>
                        </div>


                        <!-- Pricing Tab -->
                        <div class="tab-pane fade" id="pane-pricing" role="tabpanel" aria-labelledby="tab-pricing">
                            <div class="form-header">
                                <i class="fas fa-dollar-sign me-2"></i> Pricing Details
                            </div>

                            <div class="row g-4">
                                <div class="col-md-4">
                                    <label for="cost" class="form-label"><strong>Average Cost <span class="text-danger">*</span></strong></label>
                                    <div class="input-group">
                                        <span class="input-group-text">$</span>
                                        <input type="number" step="0.01" class="form-control" name="cost" id="cost" placeholder="0.00" value="{{ old('cost', $currentRecord->cost ?? '') }}">
                                    </div>
                                    <div class="field-error" id="error-cost"></div>
                                </div>

                                <div class="col-md-4">
                                    <label for="least_grv_cost" class="form-label"><strong>Last GRV Cost</strong></label>
                                    <div class="input-group">
                                        <span class="input-group-text">$</span>
                                        <input type="number" step="0.01" class="form-control" name="least_grv_cost" id="least_grv_cost" placeholder="0.00" value="{{ old('least_grv_cost', $currentRecord->least_grv_cost ?? '') }}">
                                    </div>
                                    <div class="field-error" id="error-least_grv_cost"></div>
                                </div>

                                <div class="col-md-4">
                                    <label for="min_gp_pct" class="form-label"><strong>Minimum GP %</strong></label>
                                    <div class="input-group">
                                        <input type="number" step="0.01" class="form-control" name="min_gp_pct" id="min_gp_pct" placeholder="0.00" value="{{ old('min_gp_pct', $currentRecord->min_gp_pct ?? '') }}">
                                        <span class="input-group-text">%</span>
                                    </div>
                                    <div class="field-error" id="error-min_gp_pct"></div>
                                </div>
                                <div class="col-12 col-md-4">
                                    <label for="vat_rate" class="form-label"><strong>VAT Rate %</strong></label>
                                    <div class="input-group">
                                        <input type="number" step="0.01" class="form-control" name="vat_rate" id="vat_rate" placeholder="15.00" value="{{ old('vat_rate', $currentRecord->vat_rate ?? '') }}">
                                        <span class="input-group-text">%</span>
                                    </div>
                                    <div class="field-error" id="error-vat_rate"></div>
                                </div>

                            </div>

                            <div class="table-section mt-4">
                                <h6 class="mb-3"><strong>Price List Markup:</strong></h6>
                                <div class="table-responsive">
                                    <table class="table table-hover" id="price-list-table">
                                        <thead>
                                            <tr>
                                                <th>Use</th>
                                                <th>Price List Name</th>
                                                <th>Markup %</th>
                                                <th>Excl. Price</th>
                                                <th>Incl. Price</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($priceListNames as $list)
                                                <?php
                                                    $markupValue = '';
                                                    if ($currentRecord) {
                                                        $markup = $currentRecord->priceMarkups->where('price_list_name_id', $list->id)->first();
                                                        $markupValue = $markup ? $markup->markup_pct : '';
                                                    }
                                                ?>
                                                <tr>
                                                    <td class="text-center">
                                                        <div class="form-check">
                                                            <input class="form-check-input use-price-list" type="checkbox" {{ $markupValue !== '' ? 'checked' : '' }} data-id="{{ $list->id }}">
                                                        </div>
                                                    </td>
                                                    <td>{{ $list->name }}</td>
                                                    <td>
                                                        <input type="number" step="0.01" class="form-control form-control-sm markup" name="markup[{{ $list->id }}]" placeholder="0.00 %" value="{{ $markupValue }}">
                                                    </td>
                                                    <td>
                                                        <input type="text" class="form-control form-control-sm excl-price" name="excl_price[{{ $list->id }}]" readonly placeholder="0.00">
                                                    </td>
                                                    <td>
                                                        <input type="text" class="form-control form-control-sm incl-price" name="incl_price[{{ $list->id }}]" readonly placeholder="0.00">
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            
                            <div class="btn-group-nav">
                                <button type="button" class="btn btn-outline-primary" id="btn-pricing-back">
                                    <i class="fas fa-arrow-left me-2"></i> Back
                                </button>
                                <button type="button" class="btn btn-primary" id="btn-pricing-next">
                                    Next <i class="fas fa-arrow-right ms-2"></i>
                                </button>
                            </div>
                        </div>
                        
                        <!-- Warehouse Tab -->
                        <div class="tab-pane fade" id="pane-warehouse" role="tabpanel" aria-labelledby="tab-warehouse">
                            <div class="form-header">
                                <i class="fas fa-warehouse me-2"></i> Warehouse Details
                            </div>

                            <div class="row g-4">
                                <div class="col-md-6">
                                    <label for="warehouse_id" class="form-label"><strong>Warehouse <span class="text-danger">*</span></strong></label>
                                    <select class="form-select" name="warehouse_id" id="warehouse_id">
                                        <option value="">-- Select Warehouse --</option>
                                        @foreach($warehouses as $warehouse)
                                            <option value="{{ $warehouse->id }}" 
                                                {{ old('warehouse_id', $currentRecord->warehouse_id ?? '') == $warehouse->id ? 'selected' : '' }}>
                                                {{ $warehouse->description }}
                                            </option>
                                        @endforeach
                                    </select>
                                    <div class="field-error" id="error-warehouse_id"></div>
                                </div>

                                <div class="col-md-6">
                                    <label for="warehouse_desc" class="form-label"><strong>Warehouse Description</strong></label>
                                    <input type="text" class="form-control" name="warehouse_desc" id="warehouse_desc" placeholder="Enter description" 
                                        value="{{ old('warehouse_desc', $currentRecord->warehouse_desc ?? '') }}">
                                </div>

                                <div class="col-md-6">
                                    <label for="original_quantity" class="form-label"><strong>Original Quantity</strong></label>
                                    <input type="number" step="1" class="form-control" name="original_quantity" id="original_quantity" placeholder="Quantity" 
                                        value="{{ old('original_quantity', $currentRecord->original_quantity ?? '') }}">
                                    <div class="field-error" id="error-original_quantity"></div>
                                </div>

                                <div class="col-12">
                                    <div class="card bg-light p-3">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label"><strong>On Hand</strong></label>
                                                    <div class="h4" id="on_hand">—</div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label"><strong>Current Stock</strong></label>
                                                    <div class="h4" id="current_stock">—</div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label"><strong>Available</strong></label>
                                                    <div class="h4" id="available">—</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="btn-group-nav">
                                <button type="button" class="btn btn-outline-primary" id="btn-warehouse-back">
                                    <i class="fas fa-arrow-left me-2"></i> Back
                                </button>
                                <button type="button" class="btn btn-primary" id="btn-warehouse-next">
                                    Next <i class="fas fa-arrow-right ms-2"></i>
                                </button>
                            </div>
                        </div>
                                                                    
                        <!-- Images Tab -->
                        <div class="tab-pane fade" id="pane-images" role="tabpanel" aria-labelledby="tab-images">
                            <div class="form-header">
                                <i class="fas fa-images me-2"></i> Product Images
                            </div>
                            
                            <div class="row g-4">
                                <div class="col-12">
                                    <label class="form-label"><strong>Upload Images</strong></label>
                                    <div class="image-drop-area" id="imageDropArea">
                                        <i class="fas fa-cloud-upload-alt fa-3x mb-3 text-muted"></i>
                                        <h5>Drag & drop your images here</h5>
                                        <p class="text-muted">or click to browse files</p>
                                        <small class="text-muted">(Supports JPG, PNG up to 5MB each)</small>
                                    </div>
                                    <input type="file" name="images[]" id="imagesInput" accept="image/*" multiple hidden>
                                    
                                    <div class="mt-4">
                                        <h6>Selected Images</h6>
                                        <div class="image-preview" id="selectedImagesPreview">
                                            @if($currentRecord && $currentRecord->images)
                                                @foreach($currentRecord->images as $image)
                                                    <div class="image-preview-item" data-id="{{ $image->id }}">
                                                        <img src="{{ Storage::url($image->path) }}" alt="Existing Image">
                                                        <button type="button" class="delete-existing-image">×</button>
                                                    </div>
                                                @endforeach
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="btn-group-nav">
                                <button type="button" class="btn btn-outline-primary" id="btn-images-back">
                                    <i class="fas fa-arrow-left me-2"></i> Back
                                </button>
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-check me-2"></i> Submit Item
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
<!-- Item Types Table -->
<div class="card mt-4" >
    <div class="card-body">
        <h5 class="card-title" style="font-weight: bold; font-size: 1.3em;">Item Types</h5>
        <table id="item_types_table" class="table table-bordered dt-responsive nowrap table-striped align-middle" style="width:100%">
            <thead class="table-light">
                <tr>
                    <th>Code</th>
                    <th>Description 1</th>
                    <th>Description 2</th>
                    <th>Bin Location</th>
                    <th>Warehouse</th>
                    <th>Original Quantity</th> <!-- New column header -->
                    <th>Category</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                @foreach($records as $item)
                <tr>
                    <td>{{ $item->code }}</td>
                    <td>{{ $item->description1 }}</td>
                    <td>{{ $item->description2 }}</td>
                    <td>{{ $item->binLocation->description ?? 'N/A' }}</td>
                    <td>{{ $item->warehouse->description ?? 'N/A' }}</td>
                    <td>{{ $item->original_quantity }}</td> <!-- New data cell -->
                    <td>{{ $item->category->name ?? 'N/A' }}</td>
                    <td>
                        <a href="#" class="btn btn-sm btn-primary editBtn" 
                           data-id="{{ $item->id }}"
                           data-code="{{ $item->code }}"
                           data-description1="{{ $item->description1 }}"
                           data-description2="{{ $item->description2 }}"
                           data-bin_location="{{ $item->bin_location_id }}"
                           data-warehouse="{{ $item->warehouse_id }}"
                           data-original_quantity="{{ $item->original_quantity }}" 
                           data-category="{{ $item->category_id }}"
                           data-barcode_box="{{ $item->barcode_box }}"
                           data-cost="{{ $item->cost }}"
                           data-least_grv_cost="{{ $item->least_grv_cost }}"
                           data-min_gp_pct="{{ $item->min_gp_pct }}"
                           data-vat_rate="{{ $item->vat_rate }}"
                           data-active="{{ $item->active }}"
                           data-is_service_item="{{ $item->is_service_item }}"
                           data-is_physical_item="{{ $item->is_physical_item }}"
                           data-has_warehouse="{{ $item->has_warehouse }}"
                           data-has_units_of_measure="{{ $item->has_units_of_measure }}"
                           data-stocking_unit_id="{{ $item->stocking_unit_id }}"
                           data-default_purchase_unit_id="{{ $item->default_purchase_unit_id }}"
                           data-default_sale_unit_id="{{ $item->default_sale_unit_id }}">
                            <i class="fas fa-edit"></i>
                        </a>

                        <a href="{{ route('supplier.item_types.delete', $item->id) }}" class="btn btn-danger btn-sm deleteBtn">
                            <i class="fas fa-trash-alt"></i>
                        </a>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Confirm Deletion</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                Are you sure you want to delete this item type?
            </div>
            <div class="modal-footer">
                <button id="cancelDeleteBtn" type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button id="confirmDeleteBtn" type="button" class="btn btn-danger">Delete</button>
            </div>
        </div>
    </div>
</div>

<!-- Logout Modal -->
<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
            <div class="modal-footer">
                <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                <a class="btn btn-primary" href="{{ route('logout') }}"
                    onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
                    Logout
                </a>
                <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                    @csrf
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize Bootstrap tabs
        const tabElements = [].slice.call(document.querySelectorAll('#itemTypeTabs button[data-bs-toggle="tab"]'));
        const tabList = tabElements.map(function(tabEl) {
            return new bootstrap.Tab(tabEl);
        });
        
        // Get tab buttons
        const tabItem = document.getElementById('tab-item');
        const tabInfo = document.getElementById('tab-info');
        const tabUnits = document.getElementById('tab-units');
        const tabPricing = document.getElementById('tab-pricing');
        const tabWarehouse = document.getElementById('tab-warehouse');
        const tabImages = document.getElementById('tab-images');
        const unitsTabItem = document.getElementById('units-tab-item');
        const warehouseTabItem = document.getElementById('warehouse-tab-item');
        
        // Get navigation buttons
        const btnItemNext = document.getElementById('btn-item-next');
        const btnInfoBack = document.getElementById('btn-info-back');
        const btnInfoNext = document.getElementById('btn-info-next');
        const btnUnitsBack = document.getElementById('btn-units-back');
        const btnUnitsNext = document.getElementById('btn-units-next');
        const btnPricingBack = document.getElementById('btn-pricing-back');
        const btnPricingNext = document.getElementById('btn-pricing-next');
        const btnWarehouseBack = document.getElementById('btn-warehouse-back');
        const btnWarehouseNext = document.getElementById('btn-warehouse-next');
        const btnImagesBack = document.getElementById('btn-images-back');
        
        // Progress bar
        const progressBar = document.getElementById('formProgress');
        
        // Toggle elements
        const isServiceItem = document.getElementById('is_service_item');
        const isPhysicalItem = document.getElementById('is_physical_item');
        const hasUom = document.getElementById('has_uom');
        const hasWarehouse = document.getElementById('has_warehouse');
        
        // If we are editing, enable all tabs
        @if($currentRecord)
            [tabInfo, tabUnits, tabPricing, tabWarehouse, tabImages].forEach(tab => {
                tab.classList.remove('disabled');
            });
        @endif

        // Initialize item type behavior
        function initItemTypeBehavior() {
            // If service item is checked
            if (isServiceItem.checked) {
                // Uncheck and disable physical item and warehouse
                isPhysicalItem.checked = false;
                hasWarehouse.checked = false;
                hasWarehouse.disabled = true;
            } else {
                hasWarehouse.disabled = false;
            }
            
            // Toggle units tab visibility
            if (hasUom.checked) {
                unitsTabItem.classList.remove('hidden-tab');
            } else {
                unitsTabItem.classList.add('hidden-tab');
            }
            
            // Toggle warehouse tab visibility
            if (hasWarehouse.checked && isPhysicalItem.checked) {
                warehouseTabItem.classList.remove('hidden-tab');
            } else {
                warehouseTabItem.classList.add('hidden-tab');
            }
        }
        
        // Initialize on load
        initItemTypeBehavior();
        
        // Listen for changes
        isServiceItem.addEventListener('change', function() {
            initItemTypeBehavior();
        });
        
        isPhysicalItem.addEventListener('change', function() {
            if (this.checked) {
                isServiceItem.checked = false;
            }
            initItemTypeBehavior();
        });
        
        hasUom.addEventListener('change', function() {
            initItemTypeBehavior();
        });
        
        hasWarehouse.addEventListener('change', function() {
            initItemTypeBehavior();
        });
        
        // Function to update progress bar
        function updateProgressBar(activeTab) {
            const tabs = [tabItem, tabInfo, tabUnits, tabPricing, tabWarehouse, tabImages];
            const visibleTabs = tabs.filter(tab => {
                if (tab === tabUnits) {
                    return hasUom.checked;
                }
                if (tab === tabWarehouse) {
                    return hasWarehouse.checked && isPhysicalItem.checked;
                }
                return true;
            });
            
            const activeIndex = visibleTabs.findIndex(tab => tab === activeTab);
            const progress = Math.round((activeIndex + 1) * (100 / visibleTabs.length));
            progressBar.style.width = `${progress}%`;
            progressBar.setAttribute('aria-valuenow', progress);
        }
        
        // Function to enable a tab
        function enableTab(tab) {
            tab.classList.remove('disabled');
        }
        
        // Function to switch to a specific tab
        function switchTab(tabButton) {
            bootstrap.Tab.getOrCreateInstance(tabButton).show();
            updateProgressBar(tabButton);
        }
        
        // Navigation handlers
        btnItemNext.addEventListener('click', function() {
            if (validateItemTab()) {
                enableTab(tabInfo);
                switchTab(tabInfo);
            }
        });
        
        btnInfoBack.addEventListener('click', function() {
            switchTab(tabItem);
        });
        
        btnInfoNext.addEventListener('click', function() {
            if (validateInfoTab()) {
                // Determine next tab based on visibility
                if (hasUom.checked) {
                    enableTab(tabUnits);
                    switchTab(tabUnits);
                } else if (hasWarehouse.checked && isPhysicalItem.checked) {
                    enableTab(tabPricing);
                    switchTab(tabPricing);
                } else {
                    enableTab(tabPricing);
                    switchTab(tabPricing);
                }
            }
        });
        
        btnUnitsBack.addEventListener('click', function() {
            switchTab(tabInfo);
        });
        
        btnUnitsNext.addEventListener('click', function() {
            if (hasWarehouse.checked && isPhysicalItem.checked) {
                enableTab(tabPricing);
                switchTab(tabPricing);
            } else {
                enableTab(tabPricing);
                switchTab(tabPricing);
            }
        });
        
        btnPricingBack.addEventListener('click', function() {
            // Determine previous tab based on visibility
            if (hasUom.checked) {
                switchTab(tabUnits);
            } else {
                switchTab(tabInfo);
            }
        });
        
        btnPricingNext.addEventListener('click', function() {
            if (validatePricingTab()) {
                if (hasWarehouse.checked && isPhysicalItem.checked) {
                    enableTab(tabWarehouse);
                    switchTab(tabWarehouse);
                } else {
                    enableTab(tabImages);
                    switchTab(tabImages);
                }
            }
        });
        
        btnWarehouseBack.addEventListener('click', function() {
            switchTab(tabPricing);
        });
        
        btnWarehouseNext.addEventListener('click', function() {
            if (validateWarehouseTab()) {
                enableTab(tabImages);
                switchTab(tabImages);
            }
        });
        
        btnImagesBack.addEventListener('click', function() {
            if (hasWarehouse.checked && isPhysicalItem.checked) {
                switchTab(tabWarehouse);
            } else {
                switchTab(tabPricing);
            }
        });
        
        // Validation functions
        function validateItemTab() {
            let valid = true;
            
            if (!document.getElementById('code').value) {
                document.getElementById('error-code').textContent = 'Code is required';
                valid = false;
            } else {
                document.getElementById('error-code').textContent = '';
            }
            
            if (!document.getElementById('description1').value) {
                document.getElementById('error-description1').textContent = 'Description 1 is required';
                valid = false;
            } else {
                document.getElementById('error-description1').textContent = '';
            }
            
            return valid;
        }
        
        function validateInfoTab() {
            let valid = true;
            
            if (!document.getElementById('category').value) {
                document.getElementById('error-category').textContent = 'Category is required';
                valid = false;
            } else {
                document.getElementById('error-category').textContent = '';
            }
            
            return valid;
        }
        
        function validatePricingTab() {
            let valid = true;
            
            if (!document.getElementById('cost').value || parseFloat(document.getElementById('cost').value) <= 0) {
                document.getElementById('error-cost').textContent = 'Enter a valid cost';
                valid = false;
            } else {
                document.getElementById('error-cost').textContent = '';
            }
            
            // Optional fields - no validation required
            document.getElementById('error-least_grv_cost').textContent = '';
            document.getElementById('error-min_gp_pct').textContent = '';
            
            return valid;
        }
        
        function validateWarehouseTab() {
            let valid = true;
            
            if (!document.getElementById('warehouse_id').value) {
                document.getElementById('error-warehouse_id').textContent = 'Warehouse is required';
                valid = false;
            } else {
                document.getElementById('error-warehouse_id').textContent = '';
            }
            
            return valid;
        }
        
        // Image upload functionality
        const dropArea = document.getElementById('imageDropArea');
        const imagesInput = document.getElementById('imagesInput');
        const previewDiv = document.getElementById('selectedImagesPreview');
        const deletedImagesInput = document.getElementById('deleted_images');
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter','dragover','dragleave','drop'].forEach(evt => {
            dropArea.addEventListener(evt, preventDefaults, false);
        });
        
        ['dragenter','dragover'].forEach(evt => {
            dropArea.addEventListener(evt, () => {
                dropArea.classList.add('dragover');
            }, false);
        });
        
        ['dragleave','drop'].forEach(evt => {
            dropArea.addEventListener(evt, () => {
                dropArea.classList.remove('dragover');
            }, false);
        });
        
        dropArea.addEventListener('drop', function(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            imagesInput.files = files;
            updateImagePreview(files);
        });
        
        dropArea.addEventListener('click', function() {
            imagesInput.click();
        });
        
        imagesInput.addEventListener('change', function() {
            updateImagePreview(this.files);
        });
        
        function updateImagePreview(files) {
            Array.from(files).forEach(file => {
                if (!file.type.startsWith('image/')) return;
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    const div = document.createElement('div');
                    div.className = 'image-preview-item';
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.alt = 'Upload preview';
                    
                    const deleteBtn = document.createElement('button');
                    deleteBtn.className = 'delete-existing-image';
                    deleteBtn.innerHTML = '×';
                    deleteBtn.onclick = function() {
                        div.remove();
                    };
                    
                    div.appendChild(img);
                    div.appendChild(deleteBtn);
                    previewDiv.appendChild(div);
                };
                reader.readAsDataURL(file);
            });
        }
        
        // Handle deletion of existing images
        document.querySelectorAll('.delete-existing-image').forEach(button => {
            button.addEventListener('click', function() {
                const item = this.closest('.image-preview-item');
                const imageId = item.dataset.id;
                
                if (imageId) {
                    const currentDeleted = deletedImagesInput.value ? deletedImagesInput.value.split(',') : [];
                    currentDeleted.push(imageId);
                    deletedImagesInput.value = currentDeleted.join(',');
                }
                
                item.remove();
            });
        });
        
        // Calculate prices function
        function calculatePrices() {
            const cost = parseFloat(document.getElementById('cost').value) || 0;
            const vatInput = document.getElementById('vat_rate');
            const hasVat = vatInput && vatInput.value.trim() !== '';
            const vatRate = hasVat ? parseFloat(vatInput.value) / 100 : 0;

            document.querySelectorAll('#price-list-table tbody tr').forEach(row => {
                const checkbox = row.querySelector('.use-price-list');
                const markupInput = row.querySelector('.markup');
                const exclInput = row.querySelector('.excl-price');
                const inclInput = row.querySelector('.incl-price');

                const markup = parseFloat(markupInput.value) || 0;
                const excl = cost + (cost * markup / 100);
                const incl = hasVat ? excl * (1 + vatRate) : excl; // incl = excl if no VAT

                exclInput.value = checkbox.checked ? excl.toFixed(2) : '';
                inclInput.value = checkbox.checked ? incl.toFixed(2) : '';
                exclInput.disabled = !checkbox.checked;
                inclInput.disabled = !checkbox.checked;
                markupInput.disabled = !checkbox.checked;
            });
        }

        // Initialize price calculation
        document.getElementById('cost').addEventListener('input', calculatePrices);
        document.getElementById('vat_rate').addEventListener('input', calculatePrices);
        document.querySelectorAll('.markup').forEach(input => {
            input.addEventListener('input', calculatePrices);
        });
        document.querySelectorAll('.use-price-list').forEach(input => {
            input.addEventListener('change', calculatePrices);
        });
        calculatePrices(); // Initial call
        
        // Delete confirmation modal
        let deleteUrl = null;
        const modalEl = document.getElementById('deleteConfirmModal');
        const bsModal = new bootstrap.Modal(modalEl);

        document.querySelectorAll('.deleteBtn').forEach(btn => {
            btn.addEventListener('click', function (e) {
                e.preventDefault();
                deleteUrl = this.getAttribute('href');
                bsModal.show();
            });
        });

        document.getElementById('confirmDeleteBtn').addEventListener('click', function () {
            bsModal.hide();
            window.location.href = deleteUrl;
        });

        document.getElementById('cancelDeleteBtn').addEventListener('click', function () {
            bsModal.hide();
        });
        
        // Auto fade out alerts
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            setTimeout(() => {
                alert.classList.add('fade-out');
                setTimeout(() => {
                    alert.style.display = 'none';
                }, 500);
            }, 5000);
        });
        
        // Handle Edit button to populate form for update
        document.querySelectorAll('.editBtn').forEach(btn => {
            btn.addEventListener('click', function (e) {
                e.preventDefault();

                const form = document.getElementById('itemTypeForm');
                form.action = `/supplier/item-types/update/${this.dataset.id}`;

                // Ensure PUT method is set
                let methodInput = form.querySelector('input[name="_method"]');
                if (!methodInput) {
                    methodInput = document.createElement('input');
                    methodInput.type = 'hidden';
                    methodInput.name = '_method';
                    methodInput.value = 'PUT';
                    form.appendChild(methodInput);
                } else {
                    methodInput.value = 'PUT';
                }

                // Populate form fields
                form.querySelector('[name="code"]').value = this.dataset.code;
                form.querySelector('[name="description1"]').value = this.dataset.description1;
                form.querySelector('[name="description2"]').value = this.dataset.description2;
                form.querySelector('[name="bin_location"]').value = this.dataset.bin_location;
                form.querySelector('[name="warehouse_id"]').value = this.dataset.warehouse;
                form.querySelector('[name="original_quantity"]').value = this.dataset.original_quantity; <!-- New population -->
                form.querySelector('[name="category"]').value = this.dataset.category;
                form.querySelector('[name="barcode_box"]').value = this.dataset.barcode_box;
                form.querySelector('[name="cost"]').value = this.dataset.cost;
                form.querySelector('[name="least_grv_cost"]').value = this.dataset.least_grv_cost;
                form.querySelector('[name="min_gp_pct"]').value = this.dataset.min_gp_pct;
                form.querySelector('[name="vat_rate"]').value = this.dataset.vat_rate;

                // Set checkbox states
                form.querySelector('[name="active"]').checked = this.dataset.active === '1';
                form.querySelector('[name="is_service_item"]').checked = this.dataset.is_service_item === '1';
                form.querySelector('[name="is_physical_item"]').checked = this.dataset.is_physical_item === '1';
                form.querySelector('[name="has_warehouse"]').checked = this.dataset.has_warehouse === '1';
                form.querySelector('[name="has_units_of_measure"]').checked = this.dataset.has_units_of_measure === '1';
                
                // Set unit selections
                form.querySelector('[name="stocking_unit_id"]').value = this.dataset.stocking_unit_id;
                form.querySelector('[name="default_purchase_unit_id"]').value = this.dataset.default_purchase_unit_id;
                form.querySelector('[name="default_sale_unit_id"]').value = this.dataset.default_sale_unit_id;

                // Scroll to form
                form.scrollIntoView({ behavior: 'smooth' });
                
                // Enable all tabs
                ['tab-info', 'tab-units', 'tab-pricing', 'tab-warehouse', 'tab-images'].forEach(id => {
                    document.getElementById(id).classList.remove('disabled');
                });
                
                // Trigger service item behavior
                initItemTypeBehavior();
                
                // Recalculate prices
                calculatePrices();
            });
        });
    });
    function updateWarehouseQuantities() {
        const originalQuantity = parseFloat(document.getElementById('original_quantity').value) || 0;
        const itemId = "{{ $currentRecord->id ?? '' }}";
        
        if (itemId) {
            fetch(`/supplier/item-types/${itemId}/warehouse-quantities`)
                .then(response => response.json())
                .then(data => {
                    const onHand = data.grvTotal || 0;
                    const currentStock = originalQuantity;
                    const available = onHand + originalQuantity;
                    
                    document.getElementById('on_hand').textContent = onHand;
                    document.getElementById('current_stock').textContent = currentStock;
                    document.getElementById('available').textContent = available;
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('on_hand').textContent = '0';
                    document.getElementById('current_stock').textContent = originalQuantity;
                    document.getElementById('available').textContent = originalQuantity;
                });
        } else {
            // New item - no GRV data yet
            document.getElementById('on_hand').textContent = '0';
            document.getElementById('current_stock').textContent = originalQuantity;
            document.getElementById('available').textContent = originalQuantity;
        }
    }

    // Call the function when these events occur
    document.addEventListener('DOMContentLoaded', function() {
        const warehouseTab = document.getElementById('tab-warehouse');
        const originalQuantityInput = document.getElementById('original_quantity');
        
        if (warehouseTab) {
            warehouseTab.addEventListener('shown.bs.tab', updateWarehouseQuantities);
        }
        
        if (originalQuantityInput) {
            originalQuantityInput.addEventListener('input', updateWarehouseQuantities);
        }
        
        // Initialize if warehouse tab is active on load
        if (document.querySelector('#itemTypeTabs .nav-link.active')?.id === 'tab-warehouse') {
            updateWarehouseQuantities();
        }
    });
</script>
