@extends('layouts.app')
@section('title', 'Edit Item')
@push('plugin-styles')
<style>
    .select2-container .select2-selection--single{
        height: 45px !important;
    }
</style>
@endpush
@section('content')
<div class="card">
	<div class="card-body">
		<h6 class="card-title mb-3">Edit Item</h6>

		@if($errors->any())
			<div class="alert alert-danger">
				<ul class="mb-0">
					@foreach ($errors->all() as $error)
						<li>{{ $error }}</li>
					@endforeach
				</ul>
			</div>
		@endif

		@include('items.form', ['item' => $item])
	</div>
</div>

@endsection

@push('scripts')
<script>
function addSupplier() {
    const formData = new FormData();
    formData.append('contact_id', document.getElementById('supplier_id').value);
    formData.append('is_primary', document.getElementById('is_primary').checked ? '1' : '0');
    formData.append('lead_time_days', document.getElementById('lead_time_days').value);
    formData.append('min_order_qty', document.getElementById('min_order_qty').value);
    formData.append('last_price', document.getElementById('last_price').value);
    formData.append('_token', '{{ csrf_token() }}');

    fetch('{{ route("items.suppliers.add", $item) }}', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while adding supplier');
    });
}

function removeSupplier(supplierId) {
    if (!confirm('Are you sure you want to remove this supplier?')) {
        return;
    }

    fetch(`/item-suppliers/${supplierId}`, {
        method: 'DELETE',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while removing supplier');
    });
}

function editSupplier(supplierId) {
    // This would open a modal or redirect to an edit page
    alert('Edit supplier functionality would be implemented here');
}
</script>
@endpush
