@extends('layouts.app')

@section('title', 'تعديل سند صرف')

@section('content')
<div class="container-fluid">
    @if ($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <h4 class="alert-heading">
                <i class="fas fa-exclamation-triangle"></i> أخطاء التحقق
            </h4>
            <ul class="mb-0">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    @endif

    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">تعديل سند صرف #{{ $payment->reference_number }}</h3>
                    <div class="card-tools">
                        <a href="{{ route('treasury.payments.index') }}" class="btn btn-default btn-sm">
                            <i class="fas fa-arrow-right"></i> العودة للقائمة
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form action="{{ route('treasury.payments.update', $payment->id) }}" method="POST">
                        @csrf
                        @method('PUT')
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="branch_id">الفرع <span class="text-danger">*</span></label>
                                    <select name="branch_id" id="branch_id" class="select2 form-control @error('branch_id') is-invalid @enderror" required>
                                        <option value="">-- اختر الفرع --</option>
                                        @foreach($branches as $branch)
                                            <option value="{{ $branch->id }}" {{ old('branch_id', $payment->branch_id) == $branch->id ? 'selected' : '' }}>
                                                {{ $branch->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('branch_id')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="treasury_id">الخزينة <span class="text-danger">*</span></label>
                                    <select name="treasury_id" id="treasury_id" class="select2 form-control @error('treasury_id') is-invalid @enderror" required>
                                        <option value="">-- اختر الخزينة --</option>
                                        @foreach($treasuries as $treasury)
                                            <option value="{{ $treasury->id }}" {{ old('treasury_id', $payment->treasury_id) == $treasury->id ? 'selected' : '' }}>
                                                {{ $treasury->name }} ({{ $treasury->code }}) - الرصيد: {{ number_format($treasury->current_balance, 2) }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('treasury_id')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="reference_number">رقم المرجع <span class="text-danger">*</span></label>
                                    <input type="text" name="reference_number" id="reference_number" class="form-control @error('reference_number') is-invalid @enderror" value="{{ old('reference_number', $payment->reference_number) }}" required>
                                    @error('reference_number')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="payment_date">تاريخ الصرف <span class="text-danger">*</span></label>
                                    <input type="date" name="payment_date" id="payment_date" class="form-control @error('payment_date') is-invalid @enderror" value="{{ old('payment_date', $payment->payment_date->format('Y-m-d')) }}" required>
                                    @error('payment_date')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="amount">المبلغ <span class="text-danger">*</span></label>
                                    <input type="number" step="0.01" min="0.01" name="amount" id="amount" class="form-control @error('amount') is-invalid @enderror" value="{{ old('amount', $payment->amount) }}" required>
                                    @error('amount')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="payment_type">نوع الصرف <span class="text-danger">*</span></label>
                                    <select name="payment_type" id="payment_type" class="select2 form-control @error('payment_type') is-invalid @enderror" required>
                                        <option value="">-- اختر نوع الصرف --</option>
                                        <option value="cash" {{ old('payment_type', $payment->payment_type) == 'cash' ? 'selected' : '' }}>نقدي</option>
                                        <option value="cheque" {{ old('payment_type', $payment->payment_type) == 'cheque' ? 'selected' : '' }}>شيك</option>
                                        <option value="transfer" {{ old('payment_type', $payment->payment_type) == 'transfer' ? 'selected' : '' }}>تحويل بنكي</option>
                                        <option value="other" {{ old('payment_type', $payment->payment_type) == 'other' ? 'selected' : '' }}>أخرى</option>
                                    </select>
                                    @error('payment_type')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="account_id">الحساب المصروف له <span class="text-danger">*</span></label>
                                    <select name="account_id" id="account_id" class="select2 form-control @error('account_id') is-invalid @enderror" required>
                                        <option value="">-- اختر الحساب --</option>
                                        @foreach($accounts as $account)
                                            <option value="{{ $account->id }}" {{ old('account_id', $payment->account_id) == $account->id ? 'selected' : '' }}>
                                                {{ $account->name }} ({{ $account->code }})
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('account_id')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="beneficiary_type">نوع المستفيد</label>
                                    <select name="beneficiary_type" id="beneficiary_type" class="select2 form-control @error('beneficiary_type') is-invalid @enderror">
                                        <option value="">-- اختر --</option>
                                        <option value="employee" {{ old('beneficiary_type', $payment->beneficiary_type) == 'employee' ? 'selected' : '' }}>موظف</option>
                                        <option value="supplier" {{ old('beneficiary_type', $payment->beneficiary_type) == 'supplier' ? 'selected' : '' }}>مورد</option>
                                        <option value="other" {{ old('beneficiary_type', $payment->beneficiary_type) == 'other' ? 'selected' : '' }}>أخرى</option>
                                    </select>
                                    @error('beneficiary_type')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="expense_category">فئة المصروف</label>
                                    <select name="expense_category" id="expense_category" class="select2 form-control @error('expense_category') is-invalid @enderror">
                                        <option value="">-- اختر الفئة --</option>
                                        <option value="operating_expense" {{ old('expense_category', $payment->expense_category) == 'operating_expense' ? 'selected' : '' }}>مصروف تشغيلي</option>
                                        <option value="advance" {{ old('expense_category', $payment->expense_category) == 'advance' ? 'selected' : '' }}>سلفة</option>
                                        <option value="salary" {{ old('expense_category', $payment->expense_category) == 'salary' ? 'selected' : '' }}>راتب</option>
                                        <option value="other" {{ old('expense_category', $payment->expense_category) == 'other' ? 'selected' : '' }}>أخرى</option>
                                    </select>
                                    @error('expense_category')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6" id="expense-type-container" style="display: {{ $payment->expense_category === 'operating_expense' ? 'block' : 'none' }};">
                                <div class="form-group">
                                    <label for="expense_type">نوع المصروف</label>
                                    <select name="expense_type" id="expense_type" class="select2 form-control @error('expense_type') is-invalid @enderror">
                                        <option value="">-- اختر النوع --</option>
                                        <option value="salary" {{ old('expense_type', $payment->expense_type) == 'salary' ? 'selected' : '' }}>أجور (510102)</option>
                                        <option value="contractor" {{ old('expense_type', $payment->expense_type) == 'contractor' ? 'selected' : '' }}>مقاولين (510103)</option>
                                        <option value="equipment" {{ old('expense_type', $payment->expense_type) == 'equipment' ? 'selected' : '' }}>معدات (510104)</option>
                                        <option value="direct_operating" {{ old('expense_type', $payment->expense_type) == 'direct_operating' ? 'selected' : '' }}>مصروفات تشغيلية مباشرة (510105)</option>
                                    </select>
                                    @error('expense_type')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row" id="cost-center-container" style="display: {{ $payment->expense_category === 'operating_expense' ? 'block' : 'none' }};">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="cost_center_id">مركز التكلفة <span id="cost-center-required" class="text-danger" style="display: {{ $payment->expense_category === 'operating_expense' ? 'inline' : 'none' }};">*</span></label>
                                    <select name="cost_center_id" id="cost_center_id" class="select2 form-control @error('cost_center_id') is-invalid @enderror" {{ $payment->expense_category === 'operating_expense' ? 'required' : '' }}>
                                        <option value="">-- اختر مركز التكلفة --</option>
                                        @foreach($costCenters as $costCenter)
                                            <option value="{{ $costCenter->id }}" {{ old('cost_center_id', $payment->cost_center_id) == $costCenter->id ? 'selected' : '' }}>
                                                {{ $costCenter->code }} - {{ $costCenter->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('cost_center_id')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="treasury_account">حساب الطرف الدائن <span class="text-muted" style="font-size: 0.8em;">(من الخزينة)</span></label>
                                    <input type="text" id="treasury_account" class="form-control" readonly value="">
                                    <small class="form-text text-muted d-block mt-1">يتم تحديده تلقائياً من الخزينة المختارة</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="description">الوصف</label>
                            <textarea name="description" id="description" rows="3" class="form-control @error('description') is-invalid @enderror">{{ old('description', $payment->description) }}</textarea>
                            @error('description')
                                <span class="invalid-feedback d-block">{{ $message }}</span>
                            @enderror
                        </div>
                        
                        <div class="form-group">
                            <label for="notes">ملاحظات</label>
                            <textarea name="notes" id="notes" rows="2" class="form-control @error('notes') is-invalid @enderror">{{ old('notes', $payment->notes) }}</textarea>
                            @error('notes')
                                <span class="invalid-feedback d-block">{{ $message }}</span>
                            @enderror
                        </div>

                        <div class="card mt-3">
                            <div class="card-header bg-light">
                                <h5 class="mb-0">مراكز التكلفة (اختياري)</h5>
                            </div>
                            <div class="card-body">
                                <div id="cost-centers-container">
                                    @php
                                        $existingCostCenters = old('cost_centers') ? old('cost_centers') : $payment->costCenters->pluck('id')->toArray();
                                        $existingAmounts = old('cost_center_amounts') ? old('cost_center_amounts') : $payment->costCenters->pluck('pivot.amount')->toArray();
                                        $existingPercentages = old('cost_center_percentages') ? old('cost_center_percentages') : $payment->costCenters->pluck('pivot.percentage')->toArray();
                                    @endphp
                                    
                                    @if(count($existingCostCenters) > 0)
                                        @foreach($existingCostCenters as $index => $costCenterId)
                                            <div class="cost-center-row mb-3">
                                                <div class="row">
                                                    <div class="col-md-5">
                                                        <label>مركز التكلفة</label>
                                                        <select name="cost_centers[]" class="select2 form-control">
                                                            <option value="">-- اختر مركز التكلفة --</option>
                                                            @foreach($costCenters as $costCenter)
                                                                <option value="{{ $costCenter->id }}" {{ $costCenterId == $costCenter->id ? 'selected' : '' }}>
                                                                    {{ $costCenter->code }} - {{ $costCenter->name }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <label>المبلغ</label>
                                                        <input type="number" step="0.01" name="cost_center_amounts[]" class="form-control" placeholder="0.00" value="{{ $existingAmounts[$index] ?? '' }}">
                                                    </div>
                                                    <div class="col-md-3">
                                                        <label>النسبة %</label>
                                                        <input type="number" step="0.01" name="cost_center_percentages[]" class="form-control" placeholder="0.00" value="{{ $existingPercentages[$index] ?? '' }}">
                                                    </div>
                                                    <div class="col-md-1">
                                                        <label>&nbsp;</label>
                                                        <button type="button" class="btn btn-danger btn-block remove-cost-center">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        @endforeach
                                    @else
                                        <div class="cost-center-row mb-3">
                                            <div class="row">
                                                <div class="col-md-5">
                                                    <label>مركز التكلفة</label>
                                                    <select name="cost_centers[]" class="select2 form-control">
                                                        <option value="">-- اختر مركز التكلفة --</option>
                                                        @foreach($costCenters as $costCenter)
                                                            <option value="{{ $costCenter->id }}">{{ $costCenter->code }} - {{ $costCenter->name }}</option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                                <div class="col-md-3">
                                                    <label>المبلغ</label>
                                                    <input type="number" step="0.01" name="cost_center_amounts[]" class="form-control" placeholder="0.00">
                                                </div>
                                                <div class="col-md-3">
                                                    <label>النسبة %</label>
                                                    <input type="number" step="0.01" name="cost_center_percentages[]" class="form-control" placeholder="0.00">
                                                </div>
                                                <div class="col-md-1">
                                                    <label>&nbsp;</label>
                                                    <button type="button" class="btn btn-danger btn-block remove-cost-center" style="display:none;">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    @endif
                                </div>
                                <button type="button" class="btn btn-success btn-sm" id="add-cost-center">
                                    <i class="fas fa-plus"></i> إضافة مركز تكلفة
                                </button>
                            </div>
                        </div>
                        
                        <div class="form-group mt-3">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> حفظ التغييرات
                            </button>
                            <a href="{{ route('treasury.payments.index') }}" class="btn btn-secondary">
                                <i class="fas fa-times"></i> إلغاء
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
$(document).ready(function() {
    // بيانات الخزائن والحسابات المرتبطة بها
    const treasuryAccounts = {
        @foreach($treasuries as $treasury)
            '{{ $treasury->id }}': {
                'accountName': '{{ $treasury->chartOfAccount ? $treasury->chartOfAccount->name : "لم يتم ربط حساب" }}',
                'accountCode': '{{ $treasury->chartOfAccount ? $treasury->chartOfAccount->code : "" }}'
            },
        @endforeach
    };

    // تحديث حساب الطرف الدائن عند اختيار خزينة
    $('#treasury_id').on('change', function() {
        const treasuryId = $(this).val();
        const treasuryAccountInput = $('#treasury_account');
        
        if (treasuryId && treasuryAccounts[treasuryId]) {
            const accountData = treasuryAccounts[treasuryId];
            if (accountData.accountCode) {
                treasuryAccountInput.val(accountData.accountName + ' (' + accountData.accountCode + ')');
            } else {
                treasuryAccountInput.val(accountData.accountName);
            }
        } else {
            treasuryAccountInput.val('');
        }
    });

    // عند تحميل الصفحة، إذا كانت هناك خزينة محددة (عند التعديل)
    if ($('#treasury_id').val()) {
        $('#treasury_id').trigger('change');
    }

    let costCenterRowCount = $('.cost-center-row').length;

    $('#add-cost-center').on('click', function() {
        const costCenterOptions = `@foreach($costCenters as $costCenter)<option value="{{ $costCenter->id }}">{{ $costCenter->code }} - {{ $costCenter->name }}</option>@endforeach`;
        
        const newRow = `
            <div class="cost-center-row mb-3">
                <div class="row">
                    <div class="col-md-5">
                        <label>مركز التكلفة</label>
                        <select name="cost_centers[]" class="select2 form-control">
                            <option value="">-- اختر مركز التكلفة --</option>
                            ${costCenterOptions}
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label>المبلغ</label>
                        <input type="number" step="0.01" name="cost_center_amounts[]" class="form-control" placeholder="0.00">
                    </div>
                    <div class="col-md-3">
                        <label>النسبة %</label>
                        <input type="number" step="0.01" name="cost_center_percentages[]" class="form-control" placeholder="0.00">
                    </div>
                    <div class="col-md-1">
                        <label>&nbsp;</label>
                        <button type="button" class="btn btn-danger btn-block remove-cost-center">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        $('#cost-centers-container').append(newRow);
        costCenterRowCount++;
        updateRemoveButtons();
    });

    $(document).on('click', '.remove-cost-center', function() {
        $(this).closest('.cost-center-row').remove();
        costCenterRowCount--;
        updateRemoveButtons();
    });

    function updateRemoveButtons() {
        const rows = $('.cost-center-row');
        if (rows.length === 1) {
            rows.find('.remove-cost-center').hide();
        } else {
            rows.find('.remove-cost-center').show();
        }
    }

    updateRemoveButtons();

    $('#expense_category').on('change', function() {
        const category = $(this).val();
        if (category === 'operating_expense') {
            $('#expense-type-container').show();
            $('#cost-center-container').show();
            $('#cost-center-required').show();
            $('#cost_center_id').prop('required', true);
        } else {
            $('#expense-type-container').hide();
            $('#cost-center-container').hide();
            $('#cost-center-required').hide();
            $('#cost_center_id').prop('required', false);
        }
    });

    if ($('#expense_category').val() === 'operating_expense') {
        $('#expense-type-container').show();
        $('#cost-center-container').show();
        $('#cost-center-required').show();
    }
});
</script>
@endpush
@endsection
