@extends('layouts.main')

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <h4>Add Product</h4>
    <a href="{{ route('products.index') }}" class="btn btn-secondary">
        <i class="bi bi-arrow-left"></i> Back
    </a>
</div>

@if(session('error'))
<div class="alert alert-danger">{{ session('error') }}</div>
@endif

<div class="card">
    <div class="card-body">
        <form method="POST" action="{{ route('products.store') }}" enctype="multipart/form-data">
            @csrf
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Name *</label>
                        <input type="text" name="name" class="form-control text-uppercase" value="{{ old('name') }}" oninput="this.value = this.value.toUpperCase()" required>
                        @error('name') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">SKU *</label>
                        <input type="text" name="sku" class="form-control" value="{{ old('sku') }}" required>
                        @error('sku') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Barcode</label>
                        <div class="input-group">
                            <input type="text" name="barcode" id="barcodeInput" class="form-control" value="{{ old('barcode') }}">
                            <button type="button" class="btn btn-outline-secondary" onclick="generateBarcode()" title="Generate Random Barcode">
                                <i class="bi bi-upc-scan"></i> Generate
                            </button>
                        </div>
                        @error('barcode') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                </div>
                <script>
                function generateBarcode() {
                    fetch('{{ route("products.generateBarcode") }}')
                        .then(response => response.json())
                        .then(data => {
                            document.getElementById('barcodeInput').value = data.barcode;
                            document.querySelector('input[name="sku"]').value = data.barcode;
                        })
                        .catch(error => console.error('Error generating barcode:', error));
                }
                </script>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Category *</label>
                        <div class="input-group">
                            <select name="category_id" class="form-select" id="categorySelect" required>
                                <option value="">Select Category</option>
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}" {{ old('category_id') == $category->id ? 'selected' : '' }}>
                                        {{ $category->name }}
                                    </option>
                                @endforeach
                            </select>
                            <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#quickAddCategoryModal" title="Add New Category">
                                <i class="bi bi-plus-lg"></i>
                            </button>
                        </div>
                        @error('category_id') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Unit of Measure *</label>
                        <div class="input-group">
                            <select name="unit_of_measure_id" class="form-select" id="uomSelect" required>
                                <option value="">Select Unit of Measure</option>
                                @foreach($unitOfMeasures as $uom)
                                    <option value="{{ $uom->id }}" {{ old('unit_of_measure_id') == $uom->id ? 'selected' : '' }}>
                                        {{ $uom->name }} ({{ $uom->abbreviation }})
                                    </option>
                                @endforeach
                            </select>
                            <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#quickAddUomModal" title="Add New Unit of Measure">
                                <i class="bi bi-plus-lg"></i>
                            </button>
                        </div>
                        @error('unit_of_measure_id') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <div class="mb-3">
                        <label class="form-label">Cost Price *</label>
                        <input type="number" name="cost_price" class="form-control" step="0.01" value="{{ old('cost_price') }}" required>
                        @error('cost_price') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="mb-3">
                        <label class="form-label">Selling Price *</label>
                        <input type="number" name="selling_price" class="form-control" step="0.01" value="{{ old('selling_price') }}" required>
                        @error('selling_price') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="mb-3">
                        <label class="form-label">Price 2 Name</label>
                        <input type="text" name="price_2_name" class="form-control" placeholder="e.g., Wholesale" value="{{ old('price_2_name', 'Price 2') }}">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="mb-3">
                        <label class="form-label">Price 2</label>
                        <input type="number" name="price_2" class="form-control" step="0.01" placeholder="0.00" value="{{ old('price_2') }}">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <div class="mb-3">
                        <label class="form-label">Price 3 Name</label>
                        <input type="text" name="price_3_name" class="form-control" placeholder="e.g., Bulk" value="{{ old('price_3_name', 'Price 3') }}">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="mb-3">
                        <label class="form-label">Price 3</label>
                        <input type="number" name="price_3" class="form-control" step="0.01" placeholder="0.00" value="{{ old('price_3') }}">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="mb-3">
                        <label class="form-label">Stock Quantity *</label>
                        <input type="number" name="stock_quantity" class="form-control" value="{{ old('stock_quantity', 0) }}" step="0.01" min="0" required>
                        @error('stock_quantity') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <div class="mb-3">
                        <label class="form-label">Low Stock Threshold *</label>
                        <input type="number" name="low_stock_threshold" class="form-control" value="{{ old('low_stock_threshold', 10) }}" required>
                        @error('low_stock_threshold') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Expiry Date</label>
                        <input type="date" name="expiry_date" class="form-control" value="{{ old('expiry_date') }}">
                        <small class="text-muted">Optional: Set for items with expiration</small>
                        @error('expiry_date') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Image</label>
                        <input type="file" name="image" class="form-control" accept="image/*">
                        @error('image') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Description</label>
                <textarea name="description" class="form-control" rows="2">{{ old('description') }}</textarea>
            </div>
            <button type="submit" class="btn btn-primary">Create Product</button>
        </form>
    </div>
</div>

<div class="modal fade" id="quickAddCategoryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Category Name *</label>
                    <input type="text" id="newCategoryName" class="form-control" placeholder="Enter category name" oninput="this.value = this.value.charAt(0).toUpperCase() + this.value.slice(1)">
                    <div id="categoryError" class="text-danger small mt-1" style="display: none;"></div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Description</label>
                    <textarea id="newCategoryDescription" class="form-control" rows="2" placeholder="Optional description"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveQuickCategory()">Save Category</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="quickAddUomModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Unit of Measure</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Name *</label>
                    <input type="text" id="newUomName" class="form-control" placeholder="e.g., Piece, Kilogram, Liter">
                    <div id="uomNameError" class="text-danger small mt-1" style="display: none;"></div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Abbreviation *</label>
                    <input type="text" id="newUomAbbreviation" class="form-control" placeholder="e.g., pc, kg, L">
                    <div id="uomAbbreviationError" class="text-danger small mt-1" style="display: none;"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveQuickUom()">Save Unit of Measure</button>
            </div>
        </div>
    </div>
</div>

<script>
function saveQuickCategory() {
    var name = document.getElementById('newCategoryName').value.trim();
    var description = document.getElementById('newCategoryDescription').value.trim();
    var errorDiv = document.getElementById('categoryError');
    var saveBtn = document.querySelector('#quickAddCategoryModal .btn-primary');
    
    if (!name) {
        errorDiv.textContent = 'Category name is required.';
        errorDiv.style.display = 'block';
        return;
    }
    
    errorDiv.style.display = 'none';
    saveBtn.disabled = true;
    saveBtn.textContent = 'Saving...';
    
    var formData = new FormData();
    formData.append('name', name);
    formData.append('description', description);
    
    fetch('{{ route('categories.store') }}', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: formData
    })
    .then(function(response) {
        console.log('Status:', response.status);
        if (response.status === 200 || response.status === 201) {
            return response.json().catch(function() {
                return { success: true };
            });
        }
        return response.json();
    })
    .then(function(data) {
        console.log('Response:', data);
        saveBtn.disabled = false;
        saveBtn.textContent = 'Save Category';
        
        if (data.success) {
            var categorySelect = document.getElementById('categorySelect');
            var newOption = new Option(data.category.name, data.category.id, true, true);
            categorySelect.add(newOption);
            document.querySelector('#quickAddCategoryModal .btn-close').click();
        } else {
            errorDiv.textContent = data.message || 'Error creating category.';
            errorDiv.style.display = 'block';
        }
    })
    .catch(function(error) {
        console.error('Error:', error);
        errorDiv.textContent = 'An error occurred. Please try again.';
        errorDiv.style.display = 'block';
        saveBtn.disabled = false;
        saveBtn.textContent = 'Save Category';
    });
}
</script>

<script>
function saveQuickUom() {
    var name = document.getElementById('newUomName').value.trim();
    var abbreviation = document.getElementById('newUomAbbreviation').value.trim();
    var nameError = document.getElementById('uomNameError');
    var abbrError = document.getElementById('uomAbbreviationError');
    var saveBtn = document.querySelector('#quickAddUomModal .btn-primary');
    
    nameError.style.display = 'none';
    abbrError.style.display = 'none';
    
    if (!name) {
        nameError.textContent = 'Name is required.';
        nameError.style.display = 'block';
        return;
    }
    
    if (!abbreviation) {
        abbrError.textContent = 'Abbreviation is required.';
        abbrError.style.display = 'block';
        return;
    }
    
    saveBtn.disabled = true;
    saveBtn.textContent = 'Saving...';
    
    var formData = new FormData();
    formData.append('name', name);
    formData.append('abbreviation', abbreviation);
    
    fetch('{{ route('unit-of-measures.store') }}', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: formData
    })
    .then(function(response) {
        if (response.status === 200 || response.status === 201) {
            return response.json().catch(function() {
                return { success: true };
            });
        }
        return response.json();
    })
    .then(function(data) {
        saveBtn.disabled = false;
        saveBtn.textContent = 'Save Unit of Measure';
        
        if (data.success) {
            var uomSelect = document.getElementById('uomSelect');
            var newOption = new Option(data.uom.name + ' (' + data.uom.abbreviation + ')', data.uom.id, true, true);
            uomSelect.add(newOption);
            document.querySelector('#quickAddUomModal .btn-close').click();
        } else {
            if (data.errors && data.errors.name) {
                nameError.textContent = data.errors.name[0];
                nameError.style.display = 'block';
            }
            if (data.errors && data.errors.abbreviation) {
                abbrError.textContent = data.errors.abbreviation[0];
                abbrError.style.display = 'block';
            }
        }
    })
    .catch(function(error) {
        console.error('Error:', error);
        nameError.textContent = 'An error occurred. Please try again.';
        nameError.style.display = 'block';
        saveBtn.disabled = false;
        saveBtn.textContent = 'Save Unit of Measure';
    });
}
</script>

@endsection
