@extends('layouts.app')
@section('title', \App\Helpers\TranslationHelper::transFromDatabase('Edit Invoice', __('Edit Invoice')))

@section('content')
<div class="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 py-8 px-4 md:px-8">
    <div class="max-w-7xl mx-auto">
        <!-- رأس الصفحة -->
        <div class="mb-8">
            <div class="flex items-center justify-between mb-6">
                <div>
                    <h1 class="text-4xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-edit text-blue-600 ml-3"></i>
                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Edit Invoice', __('Edit Invoice')) }}
                    </h1>
                    <p class="text-gray-600">{{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Number', __('Invoice Number')) }}: <span class="font-semibold text-blue-600">{{ $invoice->invoice_number }}</span></p>
                </div>
                <div class="flex gap-3">
                    <a href="{{ route('customer-invoices.show', $invoice->id) }}" class="inline-flex items-center px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-105">
                        <i class="fas fa-eye ml-2"></i>
                        {{ \App\Helpers\TranslationHelper::transFromDatabase('View', __('View')) }}
                    </a>
                    <a href="{{ route('customer-invoices.index') }}" class="inline-flex items-center px-6 py-3 bg-gray-600 hover:bg-gray-700 text-white font-semibold rounded-lg transition-all duration-200 shadow-md hover:shadow-lg">
                        <i class="fas fa-arrow-left ml-2"></i>
                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Return to Invoices', __('Return to Invoices')) }}
                    </a>
                </div>
            </div>
        </div>

        <!-- رسائل الخطأ -->
        @if($errors->any())
            <div class="bg-red-50 border-l-4 border-red-500 p-6 mb-6 rounded-r-lg">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-circle text-red-500 text-2xl"></i>
                    </div>
                    <div class="mr-4">
                        <h3 class="text-red-800 font-bold text-lg">{{ \App\Helpers\TranslationHelper::transFromDatabase('Validation Errors', __('Validation Errors')) }}</h3>
                        <ul class="mt-3 text-red-700 space-y-2">
                            @foreach($errors->all() as $error)
                                <li class="flex items-center"><i class="fas fa-times-circle ml-2"></i> {{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </div>
        @endif

        <form id="invoiceForm" action="{{ route('customer-invoices.update', $invoice->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')

            <!-- البيانات الأساسية -->
            <div class="bg-white rounded-xl shadow-lg p-8 mb-8 border border-gray-200">
                <h2 class="text-2xl font-bold text-gray-900 mb-6 pb-4 border-b-2 border-blue-500">
                    <i class="fas fa-info-circle text-blue-600 ml-2"></i>
                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Details', __('Invoice Details')) }}
                </h2>

                <!-- الصف الأول: العميل والعقد -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                    <div>
                        <label for="customer_id" class="block text-sm font-bold text-gray-700 mb-3">
                            <i class="fas fa-user text-blue-600 ml-2"></i>
                            {{ \App\Helpers\TranslationHelper::transFromDatabase('Customer Name', __('Customer Name')) }} <span class="text-red-600">*</span>
                        </label>
                        <select name="customer_id" id="customer_id" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 @error('customer_id') border-red-500 @enderror" required>
                            <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Customer', __('Choose Customer')) }} --</option>
                            @foreach($customers as $customer)
                                <option value="{{ $customer->id }}" {{ $invoice->customer_id == $customer->id ? 'selected' : '' }}>
                                    {{ $customer->name }}
                                </option>
                            @endforeach
                        </select>
                        @error('customer_id')
                            <p class="text-red-600 text-sm mt-2"><i class="fas fa-exclamation-circle ml-1"></i> {{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="customer_contract_id" class="block text-sm font-bold text-gray-700 mb-3">
                            <i class="fas fa-file-contract text-blue-600 ml-2"></i>
                            {{ \App\Helpers\TranslationHelper::transFromDatabase('Contract Title', __('Contract Title')) }}
                        </label>
                        <select name="customer_contract_id" id="customer_contract_id" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 @error('customer_contract_id') border-red-500 @enderror">
                            <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Contract', __('Choose Contract')) }} --</option>
                            @foreach($contracts as $contract)
                                <option value="{{ $contract->id }}" {{ $invoice->customer_contract_id == $contract->id ? 'selected' : '' }}>
                                    {{ $contract->contract_number }} - {{ $contract->title }}
                                </option>
                            @endforeach
                        </select>
                        @error('customer_contract_id')
                            <p class="text-red-600 text-sm mt-2"><i class="fas fa-exclamation-circle ml-1"></i> {{ $message }}</p>
                        @enderror
                    </div>
                </div>

                <!-- الصف الثاني: التواريخ والحالة -->
                <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                    <div>
                        <label for="invoice_number" class="block text-sm font-bold text-gray-700 mb-3">
                            <i class="fas fa-hashtag text-blue-600 ml-2"></i>
                            {{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Number', __('Invoice Number')) }}
                        </label>
                        <input type="text" name="invoice_number" id="invoice_number" class="w-full px-4 py-3 bg-gray-100 border-2 border-gray-300 rounded-lg text-gray-600 cursor-not-allowed" value="{{ $invoice->invoice_number }}" readonly>
                        <small class="text-gray-500 text-xs mt-2 block">{{ \App\Helpers\TranslationHelper::transFromDatabase('Cannot Be Changed', __('Cannot Be Changed')) }}</small>
                    </div>

                    <div>
                        <label for="invoice_date" class="block text-sm font-bold text-gray-700 mb-3">
                            <i class="fas fa-calendar-alt text-blue-600 ml-2"></i>
                            {{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Date', __('Invoice Date')) }} <span class="text-red-600">*</span>
                        </label>
                        <input type="date" name="invoice_date" id="invoice_date" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 @error('invoice_date') border-red-500 @enderror" value="{{ $invoice->invoice_date->format('Y-m-d') }}" required>
                        @error('invoice_date')
                            <p class="text-red-600 text-sm mt-2"><i class="fas fa-exclamation-circle ml-1"></i> {{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="due_date" class="block text-sm font-bold text-gray-700 mb-3">
                            <i class="fas fa-hourglass-end text-blue-600 ml-2"></i>
                            {{ \App\Helpers\TranslationHelper::transFromDatabase('Due Date', __('Due Date')) }}
                        </label>
                        <input type="date" name="due_date" id="due_date" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 @error('due_date') border-red-500 @enderror" value="{{ $invoice->due_date?->format('Y-m-d') }}">
                        @error('due_date')
                            <p class="text-red-600 text-sm mt-2"><i class="fas fa-exclamation-circle ml-1"></i> {{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="status" class="block text-sm font-bold text-gray-700 mb-3">
                            <i class="fas fa-tasks text-blue-600 ml-2"></i>
                            {{ \App\Helpers\TranslationHelper::transFromDatabase('Status', __('Status')) }} <span class="text-red-600">*</span>
                        </label>
                        <select name="status" id="status" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 @error('status') border-red-500 @enderror" required>
                            <option value="draft" {{ $invoice->status == 'draft' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Draft', __('Draft')) }}</option>
                            <option value="sent" {{ $invoice->status == 'sent' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Sent', __('Sent')) }}</option>
                            <option value="paid" {{ $invoice->status == 'paid' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Paid', __('Paid')) }}</option>
                            <option value="partially_paid" {{ $invoice->status == 'partially_paid' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Partially Paid', __('Partially Paid')) }}</option>
                            <option value="overdue" {{ $invoice->status == 'overdue' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Overdue', __('Overdue')) }}</option>
                            <option value="cancelled" {{ $invoice->status == 'cancelled' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Cancelled', __('Cancelled')) }}</option>
                        </select>
                        @error('status')
                            <p class="text-red-600 text-sm mt-2"><i class="fas fa-exclamation-circle ml-1"></i> {{ $message }}</p>
                        @enderror
                    </div>
                </div>
            </div>

            <!-- قسم البنود -->
            <div class="bg-white rounded-xl shadow-lg p-8 mb-8 border border-gray-200">
                <div class="flex items-center justify-between mb-6 pb-4 border-b-2 border-blue-500">
                    <h2 class="text-2xl font-bold text-gray-900">
                        <i class="fas fa-list text-blue-600 ml-2"></i>
                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Items', __('Invoice Items')) }} <span class="text-red-600">*</span>
                    </h2>
                    <button type="button" id="addItemBtn" class="inline-flex items-center px-6 py-3 bg-gradient-to-r from-green-600 to-green-700 hover:from-green-700 hover:to-green-800 text-white font-bold rounded-lg transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-105">
                        <i class="fas fa-plus ml-2"></i>
                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Add Item', __('Add Item')) }}
                    </button>
                </div>

                <!-- جدول البنود المحسّن -->
                <div class="overflow-x-auto">
                    <table class="w-full" id="itemsTable">
                        <thead>
                            <tr class="bg-gradient-to-r from-gray-800 to-gray-900 text-white">
                                <th class="px-6 py-4 text-right font-bold text-sm">
                                    <i class="fas fa-box text-blue-300 ml-2"></i>
                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Item', __('Item')) }}
                                </th>
                                <th class="px-6 py-4 text-right font-bold text-sm min-w-max">
                                    <i class="fas fa-ruler text-blue-300 ml-2"></i>
                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Unit', __('Unit')) }}
                                </th>
                                <th class="px-6 py-4 text-right font-bold text-sm">
                                    <i class="fas fa-align-left text-blue-300 ml-2"></i>
                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Desc', __('Desc')) }}
                                </th>
                                <th class="px-6 py-4 text-center font-bold text-sm min-w-max">
                                    <i class="fas fa-cube text-blue-300 ml-2"></i>
                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Qty', __('Qty')) }}
                                </th>
                                <th class="px-6 py-4 text-center font-bold text-sm min-w-max">
                                    <i class="fas fa-dollar-sign text-blue-300 ml-2"></i>
                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Price', __('Price')) }}
                                </th>
                                <th class="px-6 py-4 text-center font-bold text-sm min-w-max">
                                    <i class="fas fa-percentage text-blue-300 ml-2"></i>
                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Discount', __('Discount')) }}
                                </th>
                                <th class="px-6 py-4 text-center font-bold text-sm min-w-max">
                                    <i class="fas fa-tax text-blue-300 ml-2"></i>
                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Tax', __('Tax')) }}
                                </th>
                                <th class="px-6 py-4 text-center font-bold text-sm min-w-max">
                                    <i class="fas fa-sum text-blue-300 ml-2"></i>
                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Total', __('Total')) }}
                                </th>
                                <th class="px-6 py-4 text-center font-bold text-sm">
                                    <i class="fas fa-cog text-blue-300 ml-2"></i>
                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Action', __('Action')) }}
                                </th>
                            </tr>
                        </thead>
                        <tbody id="itemsBody" class="divide-y divide-gray-200">
                            @foreach($invoiceItems as $inde => $item)
                            <tr class="hover:bg-blue-50 transition-colors duration-150">
                                <td class="px-6 py-4">
                                    <select name="items[{{ $inde }}][item_id]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 item-select" data-index="{{ $inde }}" data-current-unit-id="{{ $item->itemUnit ? $item->itemUnit->id : '' }}">
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose', __('Choose')) }} --</option>
                                        @foreach($products as $product)
                                            <option value="{{ $product->id }}" {{ $item->item_id == $product->id ? 'selected' : '' }}>
                                                {{ $product->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </td>
                                <td class="px-6 py-4">
                                    <select name="items[{{ $inde }}][item_unit_id]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 item-unit-select" data-index="{{ $inde }}" {{ $item->item_id ? '' : 'disabled' }}>
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose', __('Choose')) }} --</option>
                                    </select>
                                </td>
                                <td class="px-6 py-4">
                                    <input type="text" name="items[{{ $inde }}][description]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 item-description" value="{{ $item->description }}" placeholder="الوصف">
                                </td>
                                <td class="px-6 py-4">
                                    <input type="number" name="items[{{ $inde }}][quantity]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-center font-semibold item-qty" step="0.01" min="0.01" value="{{ $item->quantity }}" required>
                                </td>
                                <td class="px-6 py-4">
                                    <input type="number" name="items[{{ $inde }}][unit_price]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-center font-semibold item-price" step="0.01" min="0" value="{{ $item->unit_price }}" required placeholder="0.00">
                                </td>
                                <td class="px-6 py-4">
                                    <input type="number" name="items[{{ $inde }}][discount_amount]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-center font-semibold item-discount" step="0.01" min="0" max="100" value="{{ $item->discount_amount }}" placeholder="0">
                                    <input type="hidden" name="items[{{ $inde }}][discount_type]" value="percentage">
                                </td>
                                <td class="px-6 py-4">
                                    <input type="number" name="items[{{ $inde }}][tax_rate]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-center font-semibold item-tax" step="0.01" min="0" max="100" value="{{ $item->tax_rate }}" placeholder="15">
                                </td>
                                <td class="px-6 py-4">
                                    <div class="px-4 py-3 bg-blue-50 border-2 border-blue-300 rounded-lg text-center font-bold text-blue-700">
                                        <span class="item-total">{{ number_format($item->total, 2) }}</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-center">
                                    <button type="button" class="inline-flex items-center px-4 py-2 bg-red-100 hover:bg-red-200 text-red-600 font-bold rounded-lg transition-all duration-150 remove-item" title="{{ \App\Helpers\TranslationHelper::transFromDatabase('Delete', __('Delete')) }}">
                                        <i class="fas fa-trash ml-1"></i>
                                    </button>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- الملخص المالي -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                <!-- المبلغ الفرعي -->
                <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-semibold">{{ \App\Helpers\TranslationHelper::transFromDatabase('Subtotal', __('Subtotal')) }}</p>
                            <p class="text-3xl font-bold text-gray-900 mt-2"><span id="subtotalDisplay">0.00</span></p>
                        </div>
                        <i class="fas fa-calculator text-blue-600 text-3xl opacity-20"></i>
                    </div>
                </div>

                <!-- الخصم -->
                <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-semibold">{{ \App\Helpers\TranslationHelper::transFromDatabase('Discount', __('Discount')) }}</p>
                            <p class="text-3xl font-bold text-red-600 mt-2">-<span id="totalDiscountDisplay">0.00</span></p>
                        </div>
                        <i class="fas fa-percentage text-red-600 text-3xl opacity-20"></i>
                    </div>
                </div>

                <!-- الضريبة -->
                <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-semibold">{{ \App\Helpers\TranslationHelper::transFromDatabase('Tax', __('Tax')) }}</p>
                            <p class="text-3xl font-bold text-orange-600 mt-2">+<span id="totalTaxDisplay">0.00</span></p>
                        </div>
                        <i class="fas fa-tax text-orange-600 text-3xl opacity-20"></i>
                    </div>
                </div>

                <!-- الإجمالي -->
                <div class="bg-gradient-to-br from-blue-600 to-blue-700 rounded-xl shadow-lg p-6 border border-blue-300">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-blue-100 text-sm font-semibold">{{ \App\Helpers\TranslationHelper::transFromDatabase('Total', __('Total')) }}</p>
                            <p class="text-3xl font-bold text-white mt-2"><span id="totalDisplay">0.00</span></p>
                        </div>
                        <i class="fas fa-sum text-blue-300 text-3xl opacity-30"></i>
                    </div>
                </div>
            </div>

            <!-- الملاحظات -->
            <div class="bg-white rounded-xl shadow-lg p-8 mb-8 border border-gray-200">
                <label for="notes" class="block text-sm font-bold text-gray-700 mb-3">
                    <i class="fas fa-sticky-note text-blue-600 ml-2"></i>
                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Notes', __('Notes')) }}
                </label>
                <textarea name="notes" id="notes" rows="4" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200" placeholder="أضف ملاحظات هنا...">{{ $invoice->notes ?? '' }}</textarea>
            </div>

            <!-- أزرار الحفظ -->
            <div class="flex gap-4 justify-end">
                <a href="{{ route('customer-invoices.index') }}" class="px-8 py-4 bg-gray-300 hover:bg-gray-400 text-gray-900 font-bold rounded-lg transition-all duration-200 shadow-md hover:shadow-lg">
                    <i class="fas fa-times ml-2"></i>
                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Cancel', __('Cancel')) }}
                </a>
                <button type="submit" class="px-8 py-4 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-bold rounded-lg transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-105">
                    <i class="fas fa-save ml-2"></i>
                    {{ \App\Helpers\TranslationHelper::transFromDatabase('Save Changes', __('Save Changes')) }}
                </button>
            </div>
        </form>
    </div>
</div>

<!-- نمط HTML لإضافة صفوف جديدة -->
<template id="itemTemplate">
    <tr class="hover:bg-blue-50 transition-colors duration-150">
        <td class="px-6 py-4">
            <select name="items[INDEX][item_id]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 item-select" data-index="INDEX">
                <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose', __('Choose')) }} --</option>
                @foreach($products as $product)
                    <option value="{{ $product->id }}">{{ $product->name }}</option>
                @endforeach
            </select>
        </td>
        <td class="px-6 py-4">
            <select name="items[INDEX][item_unit_id]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 item-unit-select" data-index="INDEX" disabled>
                <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose', __('Choose')) }} --</option>
            </select>
        </td>
        <td class="px-6 py-4">
            <input type="text" name="items[INDEX][description]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 item-description" placeholder="الوصف">
        </td>
        <td class="px-6 py-4">
            <input type="number" name="items[INDEX][quantity]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-center font-semibold item-qty" step="0.01" min="0.01" required>
        </td>
        <td class="px-6 py-4">
            <input type="number" name="items[INDEX][unit_price]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-center font-semibold item-price" step="0.01" min="0" required placeholder="0.00">
        </td>
        <td class="px-6 py-4">
            <input type="number" name="items[INDEX][discount_amount]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-center font-semibold item-discount" step="0.01" min="0" max="100" placeholder="0">
            <input type="hidden" name="items[INDEX][discount_type]" value="percentage">
        </td>
        <td class="px-6 py-4">
            <input type="number" name="items[INDEX][tax_rate]" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-center font-semibold item-tax" step="0.01" min="0" max="100" placeholder="15">
        </td>
        <td class="px-6 py-4">
            <div class="px-4 py-3 bg-blue-50 border-2 border-blue-300 rounded-lg text-center font-bold text-blue-700">
                <span class="item-total">0.00</span>
            </div>
        </td>
        <td class="px-6 py-4 text-center">
            <button type="button" class="inline-flex items-center px-4 py-2 bg-red-100 hover:bg-red-200 text-red-600 font-bold rounded-lg transition-all duration-150 remove-item">
                <i class="fas fa-trash ml-1"></i>
            </button>
        </td>
    </tr>
</template>

<script>
function loadUnitsForRow(row, itemId, currentUnitId = null) {
    const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
    fetch(`{{ route("inventory.items.units.api", ":itemId") }}`.replace(':itemId', itemId), {
        headers: {
            'X-CSRF-TOKEN': token,
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        const unitSelect = row.querySelector('.item-unit-select');
        unitSelect.innerHTML = '<option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose', __('Choose')) }} --</option>';
        if (data.success && data.data) {
            data.data.forEach(unit => {
                const option = document.createElement('option');
                option.value = unit.id;
                option.textContent = unit.unit_name;
                if (currentUnitId && unit.id == currentUnitId) {
                    option.selected = true;
                }
                unitSelect.appendChild(option);
            });
            unitSelect.disabled = false;
        }
    })
    .catch(error => console.error('خطأ:', error));
}

document.getElementById('addItemBtn')?.addEventListener('click', function() {
    const template = document.getElementById('itemTemplate');
    const tbody = document.getElementById('itemsBody');
    const newIndex = tbody.querySelectorAll('tr').length;
    
    const newRow = template.content.cloneNode(true);
    const html = new XMLSerializer().serializeToString(newRow);
    const updatedHtml = html.replace(/\[INDEX\]/g, `[${newIndex}]`);
    
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = updatedHtml;
    const newElement = tempDiv.firstElementChild;
    tbody.appendChild(newElement);
    
    attachItemEventListeners();
});

function attachItemEventListeners() {
    document.querySelectorAll('.item-select').forEach(select => {
        select.removeEventListener('change', handleItemChange);
        select.addEventListener('change', handleItemChange);
    });

    document.querySelectorAll('.item-qty, .item-price, .item-discount, .item-tax').forEach(input => {
        input.removeEventListener('input', calculateTotals);
        input.addEventListener('input', calculateTotals);
    });

    document.querySelectorAll('.remove-item').forEach(btn => {
        btn.removeEventListener('click', handleRemoveItem);
        btn.addEventListener('click', handleRemoveItem);
    });
}

function handleItemChange(e) {
    const row = e.target.closest('tr');
    const itemId = e.target.value;
    if (itemId) {
        loadUnitsForRow(row, itemId);
    } else {
        const unitSelect = row.querySelector('.item-unit-select');
        unitSelect.innerHTML = '<option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose', __('Choose')) }} --</option>';
        unitSelect.disabled = true;
    }
}

function handleRemoveItem(e) {
    e.preventDefault();
    const rows = document.querySelectorAll('#itemsBody tr');
    if (rows.length > 1) {
        e.target.closest('tr').remove();
        calculateTotals();
    } else {
        alert('{{ \App\Helpers\TranslationHelper::transFromDatabase('At Least One Item Required', __('At Least One Item Required')) }}');
    }
}

function calculateTotals() {
    let subtotal = 0;
    let totalDiscount = 0;
    let totalTax = 0;

    document.querySelectorAll('#itemsBody tr').forEach(row => {
        const qty = parseFloat(row.querySelector('.item-qty').value) || 0;
        const price = parseFloat(row.querySelector('.item-price').value) || 0;
        const discountPct = parseFloat(row.querySelector('.item-discount').value) || 0;
        const taxPct = parseFloat(row.querySelector('.item-tax').value) || 0;

        const lineSubtotal = qty * price;
        const discountAmount = (lineSubtotal * discountPct) / 100;
        const taxableAmount = lineSubtotal - discountAmount;
        const taxAmount = (taxableAmount * taxPct) / 100;
        const lineTotal = taxableAmount + taxAmount;

        row.querySelector('.item-total').textContent = lineTotal.toFixed(2);

        subtotal += lineSubtotal;
        totalDiscount += discountAmount;
        totalTax += taxAmount;
    });

    const total = subtotal - totalDiscount + totalTax;

    document.getElementById('subtotalDisplay').textContent = subtotal.toFixed(2);
    document.getElementById('totalDiscountDisplay').textContent = totalDiscount.toFixed(2);
    document.getElementById('totalTaxDisplay').textContent = totalTax.toFixed(2);
    document.getElementById('totalDisplay').textContent = total.toFixed(2);
}

document.getElementById('invoiceForm').addEventListener('submit', function(e) {
    const items = document.querySelectorAll('#itemsBody tr').length;
    if (items === 0) {
        e.preventDefault();
        alert('{{ \App\Helpers\TranslationHelper::transFromDatabase('At Least One Item Required', __('At Least One Item Required')) }}');
        return false;
    }
});

window.addEventListener('load', function() {
    document.querySelectorAll('.item-select').forEach(select => {
        const itemId = select.value;
        const row = select.closest('tr');
        const currentUnitId = select.getAttribute('data-current-unit-id');
        if (itemId) {
            loadUnitsForRow(row, itemId, currentUnitId);
        }
    });
    
    attachItemEventListeners();
    calculateTotals();
});
</script>

<style>
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

input[type="number"] {
    -moz-appearance: textfield;
}

select {
    background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: left 1rem center;
    background-size: 1.5em 1.5em;
    padding-right: 2.5rem;
}

@media (max-width: 1024px) {
    table { font-size: 0.875rem; }
    .px-6 { padding-left: 0.75rem !important; padding-right: 0.75rem !important; }
}
</style>
@endsection
