@extends('layouts.app')
@section('title', 'تعيين مراكز التكلفة')

@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-3xl font-bold text-gray-900 mb-2">تعيين مراكز التكلفة</h1>
                    <p class="text-gray-600">الفاتورة رقم: {{ $invoice->invoice_number }}</p>
                </div>
                <a href="{{ route('customer-invoices.show', $invoice->id) }}" class="inline-flex items-center px-8 py-4 bg-blue-600 text-white font-bold text-lg rounded-lg hover:bg-blue-700 transition-all duration-200 shadow-lg border-2 border-blue-700">
                    <i class="fas fa-arrow-right ml-2"></i>
                    <span>العودة</span>
                </a>
            </div>
        </div>

        @if(session('success'))
        <div class="bg-green-50 border-l-4 border-green-500 p-4 mb-6 rounded-r-lg">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-check-circle text-green-500 text-xl"></i>
                </div>
                <div class="mr-3">
                    <p class="text-green-700 font-medium">{{ session('success') }}</p>
                </div>
            </div>
        </div>
        @endif

        @if($errors->any())
        <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-6 rounded-r-lg">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-exclamation-circle text-red-500 text-xl"></i>
                </div>
                <div class="mr-3">
                    <p class="text-red-700 font-medium">يرجى تصحيح الأخطاء التالية:</p>
                    <ul class="list-disc list-inside mt-2 text-red-600">
                        @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            </div>
        </div>
        @endif

        <form action="{{ route('customer-invoices.cost-centers.update', $invoice->id) }}" method="POST" id="costCenterForm">
            @csrf
            @method('PUT')

            <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200 mb-6">
                <div class="bg-gradient-to-r from-blue-600 to-blue-700 px-6 py-4">
                    <h2 class="text-xl font-bold text-white">معلومات الفاتورة</h2>
                </div>
                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">العميل</label>
                            <p class="text-lg font-semibold text-gray-900">{{ $invoice->customer->name }}</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">تاريخ الفاتورة</label>
                            <p class="text-lg font-semibold text-gray-900">{{ $invoice->invoice_date->format('Y-m-d') }}</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">إجمالي الفاتورة</label>
                            <p class="text-lg font-semibold text-blue-600">{{ number_format($invoice->total_amount, 2) }} ريال</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200">
                <div class="bg-gradient-to-r from-purple-600 to-purple-700 px-6 py-5 flex justify-between items-center">
                    <h2 class="text-2xl font-bold text-white drop-shadow-lg">مراكز التكلفة</h2>
                    <button type="button" onclick="addCostCenter()" class="inline-flex items-center px-6 py-3 bg-yellow-400 text-gray-900 font-bold text-base rounded-lg hover:bg-yellow-500 transition-all duration-200 shadow-lg border-2 border-yellow-500">
                        <i class="fas fa-plus ml-2"></i>
                        <span>إضافة مركز تكلفة</span>
                    </button>
                </div>
                <div class="p-6">
                    <div id="costCentersContainer">
                        @if(old('cost_centers') || $invoice->costCenters->count() > 0)
                            @php
                                $costCentersData = old('cost_centers', $invoice->costCenters->toArray());
                            @endphp
                            @foreach($costCentersData as $index => $costCenter)
                                @include('customer-invoices.cost-centers.partials.cost-center-row', [
                                    'index' => $index,
                                    'costCenter' => $costCenter,
                                    'costCenters' => $costCenters
                                ])
                            @endforeach
                        @else
                            @include('customer-invoices.cost-centers.partials.cost-center-row', [
                                'index' => 0,
                                'costCenter' => null,
                                'costCenters' => $costCenters
                            ])
                        @endif
                    </div>

                    <div class="mt-6 p-4 bg-gradient-to-r from-blue-100 to-indigo-100 rounded-lg border-2 border-blue-300">
                        <div class="flex justify-between items-center">
                            <span class="text-lg font-bold text-gray-800">الإجمالي:</span>
                            <div class="text-right">
                                <p class="text-base font-semibold text-gray-800">النسبة: <span id="totalPercentage" class="font-bold text-blue-700">0.00%</span></p>
                                <p class="text-base font-semibold text-gray-800">المبلغ: <span id="totalAmount" class="font-bold text-blue-700">0.00</span> ريال</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="mt-6 flex justify-end gap-4">
                <a href="{{ route('customer-invoices.show', $invoice->id) }}" class="inline-flex items-center px-8 py-4 bg-gray-500 text-white font-bold text-lg rounded-lg hover:bg-gray-600 transition-all duration-200 shadow-lg border-2 border-gray-600">
                    <i class="fas fa-times ml-2"></i>
                    <span>إلغاء</span>
                </a>
                <button type="submit" class="inline-flex items-center px-8 py-4 bg-green-600 text-white font-bold text-lg rounded-lg hover:bg-green-700 transition-all duration-200 shadow-lg border-2 border-green-700 transform hover:scale-105">
                    <i class="fas fa-save ml-2"></i>
                    <span>حفظ</span>
                </button>
            </div>
        </form>
    </div>
</div>

<template id="costCenterRowTemplate">
    @include('customer-invoices.cost-centers.partials.cost-center-row', [
        'index' => '__INDEX__',
        'costCenter' => null,
        'costCenters' => $costCenters
    ])
</template>

@push('scripts')
<script>
let rowIndex = {{ old('cost_centers') ? count(old('cost_centers')) : ($invoice->costCenters->count() > 0 ? $invoice->costCenters->count() : 1) }};
const invoiceTotal = {{ $invoice->total_amount }};

function addCostCenter() {
    const template = document.getElementById('costCenterRowTemplate').innerHTML;
    const newRow = template.replace(/__INDEX__/g, rowIndex);
    document.getElementById('costCentersContainer').insertAdjacentHTML('beforeend', newRow);
    rowIndex++;
    updateTotals();
}

function removeCostCenter(button) {
    const row = button.closest('.cost-center-row');
    if (document.querySelectorAll('.cost-center-row').length > 1) {
        row.remove();
        updateTotals();
    } else {
        alert('يجب أن يكون هناك مركز تكلفة واحد على الأقل');
    }
}

function updateAllocation(index) {
    const allocationType = document.querySelector(`select[name="cost_centers[${index}][allocation_type]"]`).value;
    const percentageInput = document.querySelector(`input[name="cost_centers[${index}][percentage]"]`);
    const amountInput = document.querySelector(`input[name="cost_centers[${index}][amount]"]`);

    if (allocationType === 'percentage') {
        percentageInput.disabled = false;
        amountInput.disabled = true;
        amountInput.value = '';
        percentageInput.focus();
    } else {
        percentageInput.disabled = true;
        amountInput.disabled = false;
        percentageInput.value = '';
        amountInput.focus();
    }

    updateTotals();
}

function calculateFromPercentage(index) {
    const percentage = parseFloat(document.querySelector(`input[name="cost_centers[${index}][percentage]"]`).value) || 0;
    const amount = (invoiceTotal * percentage) / 100;
    document.querySelector(`input[name="cost_centers[${index}][amount]"]`).value = amount.toFixed(2);
    updateTotals();
}

function calculateFromAmount(index) {
    const amount = parseFloat(document.querySelector(`input[name="cost_centers[${index}][amount]"]`).value) || 0;
    const percentage = (amount / invoiceTotal) * 100;
    document.querySelector(`input[name="cost_centers[${index}][percentage]"]`).value = percentage.toFixed(2);
    updateTotals();
}

function updateTotals() {
    let totalPercentage = 0;
    let totalAmount = 0;

    document.querySelectorAll('.cost-center-row').forEach((row, index) => {
        const allocationType = row.querySelector('select[name*="[allocation_type]"]').value;
        
        if (allocationType === 'percentage') {
            const percentage = parseFloat(row.querySelector('input[name*="[percentage]"]').value) || 0;
            totalPercentage += percentage;
            totalAmount += (invoiceTotal * percentage) / 100;
        } else {
            const amount = parseFloat(row.querySelector('input[name*="[amount]"]').value) || 0;
            totalAmount += amount;
            totalPercentage += (amount / invoiceTotal) * 100;
        }
    });

    document.getElementById('totalPercentage').textContent = totalPercentage.toFixed(2) + '%';
    document.getElementById('totalAmount').textContent = totalAmount.toFixed(2);

    if (Math.abs(totalPercentage - 100) > 0.01 && totalPercentage > 0) {
        document.getElementById('totalPercentage').classList.add('text-red-600');
        document.getElementById('totalPercentage').classList.remove('text-blue-600');
    } else {
        document.getElementById('totalPercentage').classList.add('text-blue-600');
        document.getElementById('totalPercentage').classList.remove('text-red-600');
    }

    if (Math.abs(totalAmount - invoiceTotal) > 0.01 && totalAmount > 0) {
        document.getElementById('totalAmount').classList.add('text-red-600');
        document.getElementById('totalAmount').classList.remove('text-blue-600');
    } else {
        document.getElementById('totalAmount').classList.add('text-blue-600');
        document.getElementById('totalAmount').classList.remove('text-red-600');
    }
}

document.addEventListener('DOMContentLoaded', function() {
    updateTotals();
});
</script>
@endpush
@endsection
