<div>
    <x-layouts.app title="{{ $isEditing ? __('Edit Journal Entry') : __('New Journal Entry') }}">
        <div class="page-header d-flex justify-content-between align-items-center">
            <div>
                <h1 class="page-title">{{ $isEditing ? __('Edit Journal Entry') : __('New Journal Entry') }}</h1>
                <p class="text-muted mb-0">{{ __('Create a double-entry journal transaction') }}</p>
            </div>
            @if($isEditing)
                <span class="badge bg-{{ $entry->status === 'posted' ? 'success' : ($entry->status === 'pending' ? 'warning' : ($entry->status === 'draft' ? 'secondary' : 'danger')) }} fs-6">
                    {{ __(ucfirst($entry->status)) }}
                </span>
            @endif
        </div>

        @if(session('error'))
            <div class="alert alert-danger alert-dismissible fade show">{{ session('error') }}<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        @endif

        @if($isEditing && $entry->status === 'posted')
            @if(auth()->user()->isSuperAdmin())
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>{{ __('Warning: You are editing a POSTED journal entry. Changes will be audited.') }}
                </div>
            @else
                <div class="alert alert-info">
                    <i class="fas fa-lock me-2"></i>{{ __('This journal entry is posted and cannot be edited.') }}
                </div>
            @endif
        @endif

        <form wire:submit="save">
            <!-- Header Card -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">{{ __('Entry Details') }}</h5>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">{{ __('Date') }} <span class="text-danger">*</span></label>
                            <input type="date" class="form-control @error('entry_date') is-invalid @enderror" wire:model="entry_date"
                                   @if($isEditing && $entry->status === 'posted' && !auth()->user()->isSuperAdmin()) disabled @endif>
                            @error('entry_date') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">{{ __('Reference') }}</label>
                            <input type="text" class="form-control" wire:model="reference" placeholder="{{ __('Invoice #, etc.') }}"
                                   @if($isEditing && $entry->status === 'posted' && !auth()->user()->isSuperAdmin()) disabled @endif>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('Description') }}</label>
                            <input type="text" class="form-control" wire:model="description" placeholder="{{ __('Entry description') }}"
                                   @if($isEditing && $entry->status === 'posted' && !auth()->user()->isSuperAdmin()) disabled @endif>
                        </div>
                        <div class="col-md-3">
                             <label class="form-label">{{ __('Partner') }}</label>
                             <select class="form-select @error('partner_id') is-invalid @enderror" wire:model="partner_id"
                                     @if($isEditing && $entry->status === 'posted' && !auth()->user()->isSuperAdmin()) disabled @endif>
                                 <option value="">{{ __('Select Partner (Optional)') }}</option>
                                 @foreach($partners as $partner)
                                     <option value="{{ $partner->id }}">
                                         {{ $partner->name }}
                                     </option>
                                 @endforeach
                             </select>
                             @error('partner_id') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                </div>
            </div>

            <!-- Lines Card -->
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">{{ __('Entry Lines') }}</h5>
                    @if(!$isEditing || $entry->status !== 'posted' || auth()->user()->isSuperAdmin())
                        <button type="button" class="btn btn-sm btn-success" wire:click="addLine">
                            <i class="fas fa-plus me-1"></i>{{ __('Add Line') }}
                        </button>
                    @endif
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-bordered mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th style="width: 40%;">{{ __('Account') }}</th>
                                    <th style="width: 25%;">{{ __('Description') }}</th>
                                    <th class="text-end" style="width: 15%;">{{ __('Debit') }}</th>
                                    <th class="text-end" style="width: 15%;">{{ __('Credit') }}</th>
                                    <th style="width: 50px;"></th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($lines as $index => $line)
                                    <tr wire:key="line-{{ $index }}">
                                        <td>
                                            <select class="form-select form-select-sm @error('lines.'.$index.'.account_id') is-invalid @enderror" 
                                                    wire:model="lines.{{ $index }}.account_id"
                                                    @if($isEditing && $entry->status === 'posted' && !auth()->user()->isSuperAdmin()) disabled @endif>
                                                <option value="">{{ __('Select Account') }}</option>
                                                @foreach($accounts as $account)
                                                    <option value="{{ $account->id }}">{{ $account->code }} - {{ $account->name }}</option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control form-control-sm" 
                                                   wire:model="lines.{{ $index }}.description" placeholder="{{ __('Line memo') }}"
                                                   @if($isEditing && $entry->status === 'posted' && !auth()->user()->isSuperAdmin()) disabled @endif>
                                        </td>
                                        <td>
                                            <input type="number" step="0.01" min="0" 
                                                   class="form-control form-control-sm text-end"
                                                   wire:model.live="lines.{{ $index }}.debit"
                                                   placeholder="0.00"
                                                   @if($isEditing && $entry->status === 'posted' && !auth()->user()->isSuperAdmin()) disabled @endif>
                                        </td>
                                        <td>
                                            <input type="number" step="0.01" min="0"
                                                   class="form-control form-control-sm text-end"
                                                   wire:model.live="lines.{{ $index }}.credit"
                                                   placeholder="0.00"
                                                   @if($isEditing && $entry->status === 'posted' && !auth()->user()->isSuperAdmin()) disabled @endif>
                                        </td>
                                        <td class="text-center">
                                            @if(count($lines) > 2 && (!$isEditing || $entry->status !== 'posted' || auth()->user()->isSuperAdmin()))
                                                <button type="button" class="btn btn-sm btn-outline-danger" wire:click="removeLine({{ $index }})">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            @endif
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                            <tfoot class="table-light">
                                <tr>
                                    <td colspan="2" class="text-end"><strong>{{ __('Total') }}</strong></td>
                                    <td class="text-end"><strong>{{ number_format($totalDebit, 2) }}</strong></td>
                                    <td class="text-end"><strong>{{ number_format($totalCredit, 2) }}</strong></td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td colspan="2" class="text-end">{{ __('Difference') }}</td>
                                    <td colspan="2" class="text-center">
                                        @if($isBalanced)
                                            <span class="badge bg-success"><i class="fas fa-check me-1"></i>{{ __('Balanced') }}</span>
                                        @else
                                            <span class="badge bg-danger">
                                                <i class="fas fa-times me-1"></i>{{ number_format(abs($totalDebit - $totalCredit), 2) }}
                                            </span>
                                        @endif
                                    </td>
                                    <td></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Actions -->
            <div class="d-flex justify-content-between">
                <a href="{{ route('accounting.journals') }}" class="btn btn-secondary">
                    <i class="fas fa-arrow-left me-2"></i>{{ __('Back') }}
                </a>
                @if(!$isEditing || $entry->status !== 'posted' || auth()->user()->isSuperAdmin())
                    <button type="submit" class="btn btn-primary btn-lg" @if(!$isBalanced) disabled @endif>
                        <i class="fas fa-save me-2"></i>{{ __('Save Entry') }}
                    </button>
                @endif
            </div>
        </form>

        {{-- Edit History / Audit Trail --}}
        @if($isEditing && count($auditLogs) > 0)
            <div class="card mt-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-history me-2"></i>{{ __('Edit History') }}</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-sm table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>{{ __('Date & Time') }}</th>
                                    <th>{{ __('User') }}</th>
                                    <th>{{ __('Action') }}</th>
                                    <th>{{ __('Details') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($auditLogs as $log)
                                    <tr>
                                        <td>{{ $log->created_at->format('Y-m-d H:i:s') }}</td>
                                        <td>
                                            <i class="fas fa-user me-1"></i>
                                            {{ $log->user?->name ?? __('System') }}
                                        </td>
                                        <td>
                                            <span class="badge bg-{{ $log->action_color }}">{{ $log->action_label }}</span>
                                        </td>
                                        <td>
                                            @if($log->changes)
                                                @if(isset($log->changes['status']))
                                                    {{ __('Status changed from') }} 
                                                    <strong>{{ ucfirst($log->changes['status']['from'] ?? '?') }}</strong>
                                                    → <strong>{{ ucfirst($log->changes['status']['to'] ?? '?') }}</strong>
                                                @elseif(isset($log->changes['old']))
                                                    @php
                                                        $diffs = [];
                                                        $old = $log->changes['old'] ?? [];
                                                        $new = $log->changes['new'] ?? [];
                                                        foreach ($new as $key => $val) {
                                                            if (isset($old[$key]) && $old[$key] != $val) {
                                                                $diffs[] = ucfirst(str_replace('_', ' ', $key));
                                                            }
                                                        }
                                                    @endphp
                                                    @if(count($diffs) > 0)
                                                        {{ __('Changed:') }} {{ implode(', ', $diffs) }}
                                                    @else
                                                        {{ __('Entry updated') }}
                                                    @endif
                                                @else
                                                    <small class="text-muted">{{ json_encode($log->changes) }}</small>
                                                @endif
                                            @else
                                                -
                                            @endif
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        @endif
    </x-layouts.app>
</div>
