﻿@extends('layouts.app')

@section('content')
<div class="container mx-auto px-4 sm:px-6 lg:px-8">
    <div class="bg-white rounded-lg shadow-lg p-6">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold text-gray-900">إنشاء إذن تحويل جديد</h1>
            <a href="{{ route('inventory.transfers.index') }}" class="inline-flex items-center px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
                <svg class="h-5 w-5 ml-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                </svg>
                العودة للقائمة
            </a>
        </div>

        <form action="{{ route('inventory.transfers.store') }}" method="POST">
            @csrf

            <!-- Document Details -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
                <div>
                    <label for="document_number" class="block text-sm font-medium text-gray-700 mb-1">رقم المستند</label>
                    <input type="text" id="document_number" name="document_number" value="{{ old('document_number') }}" required class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                    @error('document_number')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>
                
                <div>
                    <label for="document_date" class="block text-sm font-medium text-gray-700 mb-1">تاريخ المستند</label>
                    <input type="date" id="document_date" name="document_date" value="{{ old('document_date', date('Y-m-d')) }}" required class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                    @error('document_date')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>
                
                <div>
                    <label for="from_warehouse_id" class="block text-sm font-medium text-gray-700 mb-1">المخزن المصدر</label>
                    <select id="from_warehouse_id" name="from_warehouse_id" required class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                        <option value="">اختر المخزن</option>
                        @foreach($warehouses as $warehouse)
                            <option value="{{ $warehouse->id }}" {{ old('from_warehouse_id') == $warehouse->id ? 'selected' : '' }}>{{ $warehouse->name }}</option>
                        @endforeach
                    </select>
                    @error('from_warehouse_id')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>
                
                <div>
                    <label for="to_warehouse_id" class="block text-sm font-medium text-gray-700 mb-1">المخزن الوجهة</label>
                    <select id="to_warehouse_id" name="to_warehouse_id" required class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                        <option value="">اختر المخزن</option>
                        @foreach($warehouses as $warehouse)
                            <option value="{{ $warehouse->id }}" {{ old('to_warehouse_id') == $warehouse->id ? 'selected' : '' }}>{{ $warehouse->name }}</option>
                        @endforeach
                    </select>
                    @error('to_warehouse_id')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            <div class="mb-6">
                <label for="notes" class="block text-sm font-medium text-gray-700 mb-1">ملاحظات</label>
                <textarea id="notes" name="notes" rows="3" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">{{ old('notes') }}</textarea>
                @error('notes')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
            </div>

            <!-- Document Items -->
            <div class="mb-6">
                <div class="flex justify-between items-center mb-3">
                    <h2 class="text-lg font-semibold text-gray-900">الأصناف</h2>
                    <button type="button" id="add-item" class="inline-flex items-center px-3 py-1 bg-primary-600 text-white text-sm rounded-md hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                        <svg class="h-4 w-4 ml-1" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                        </svg>
                        إضافة صنف
                    </button>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200" id="items-table">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الصنف</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الوحدة</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الكمية</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">التكلفة</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الإجمالي</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">ملاحظات</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="items-container">
                            <!-- Items will be added here dynamically -->
                        </tbody>
                        <tfoot class="bg-gray-50">
                            <tr>
                                <td colspan="4" class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 text-left">الإجمالي</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900" id="total-cost">0.00</td>
                                <td colspan="2"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
                
                @error('item_ids')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
                
                @error('item_ids.*')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
            </div>

            <div class="flex justify-end">
                <button type="submit" class="inline-flex items-center px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                    <svg class="h-5 w-5 ml-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                    </svg>
                    حفظ
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Item Template -->
<template id="item-template">
    <tr class="item-row">
        <td class="px-6 py-4 whitespace-nowrap">
            <select name="item_ids[]" required class="item-select block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                <option value="">اختر الصنف</option>
                @foreach($items as $item)
                    <option value="{{ $item->id }}" data-primary-unit="{{ $item->primary_unit_id }}">{{ $item->name }}</option>
                @endforeach
            </select>
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <select name="unit_ids[]" required class="unit-select block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                <option value="">اختر الوحدة</option>
                <!-- Units will be populated dynamically -->
            </select>
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <input type="number" name="quantities[]" step="0.01" min="0.01" required class="quantity-input block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <input type="number" name="unit_costs[]" step="0.01" min="0" required class="cost-input block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <input type="number" step="0.01" readonly class="total-input block w-full rounded-md border-gray-300 bg-gray-50 shadow-sm">
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <input type="text" name="item_notes[]" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <button type="button" class="remove-item text-red-600 hover:text-red-900">
                <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
            </button>
        </td>
    </tr>
</template>

@endsection

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Add first item row by default
        addItemRow();
        
        // Add Item Button
        document.getElementById('add-item').addEventListener('click', function() {
            addItemRow();
        });
        
        // Remove Item Button (using event delegation)
        document.getElementById('items-container').addEventListener('click', function(e) {
            if (e.target.closest('.remove-item')) {
                const row = e.target.closest('.item-row');
                if (document.querySelectorAll('.item-row').length > 1) {
                    row.remove();
                    updateTotalCost();
                }
            }
        });
        
        // Item Selection Change (using event delegation)
        document.getElementById('items-container').addEventListener('change', function(e) {
            if (e.target.classList.contains('item-select')) {
                const row = e.target.closest('.item-row');
                const unitSelect = row.querySelector('.unit-select');
                const selectedOption = e.target.options[e.target.selectedIndex];
                
                // Clear existing options
                unitSelect.innerHTML = '<option value="">اختر الوحدة</option>';
                
                if (e.target.value) {
                    // Add primary unit
                    const primaryUnitId = selectedOption.dataset.primaryUnit;
                    
                    // Fetch units for this item via AJAX
fetch(`{{ route("inventory.items.units.api", ":itemId") }}`.replace(':itemId', e.target.value), { credentials: "same-origin" })

                    .then(response => response.json())
                        .then(data => {
                            data.data.forEach(unit => {
                                const option = document.createElement('option');
                                option.value = unit.id;
                                option.textContent = unit.unit_name;
                                if (unit.id == primaryUnitId) {
                                    option.selected = true;
                                }
                                unitSelect.appendChild(option);
                            });
                        })
                        .catch(error => {
                            console.error('Error fetching units:', error);
                        });
                }
            }
        });
        
        // Calculate row total and update total cost
        document.getElementById('items-container').addEventListener('input', function(e) {
            if (e.target.classList.contains('quantity-input') || e.target.classList.contains('cost-input')) {
                const row = e.target.closest('.item-row');
                const quantity = parseFloat(row.querySelector('.quantity-input').value) || 0;
                const unitCost = parseFloat(row.querySelector('.cost-input').value) || 0;
                const totalInput = row.querySelector('.total-input');
                
                const total = quantity * unitCost;
                totalInput.value = total.toFixed(2);
                
                updateTotalCost();
            }
        });
        
        function addItemRow() {
            const template = document.getElementById('item-template');
            const clone = document.importNode(template.content, true);
            document.getElementById('items-container').appendChild(clone);
        }
        
        function updateTotalCost() {
            const totalInputs = document.querySelectorAll('.total-input');
            let total = 0;
            
            totalInputs.forEach(input => {
                total += parseFloat(input.value) || 0;
            });
            
            document.getElementById('total-cost').textContent = total.toFixed(2);
        }
    });
</script>
@endpush