{{-- resources/views/accounting/partials/journal-modals.blade.php --}}

{{-- Create/Edit Journal Entry Modal --}}
<div class="modal fade" id="journalModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="journalModalTitle">Create Journal Entry</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="journalForm">
                @csrf
                <input type="hidden" id="journalId" name="id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="journalDate" name="date" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Reference</label>
                            <input type="text" class="form-control" id="journalReference" name="reference">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Template</label>
                            <select class="form-select" id="journalTemplate" onchange="loadTemplate(this.value)">
                                <option value="">Manual Entry</option>
                                @foreach($templates ?? [] as $code => $name)
                                    <option value="{{ $code }}">{{ $code }} - {{ $name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="journalDescription" name="description" rows="2" required></textarea>
                    </div>
                    
                    <h6 class="mt-4 mb-3">Journal Items</h6>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Account</th>
                                    <th>Description</th>
                                    <th class="text-end">Debit</th>
                                    <th class="text-end">Credit</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody id="journalItems">
                                <tr>
                                    <td>
                                        <select class="form-select form-select-sm" name="items[0][account_id]" required>
                                            <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" name="items[0][description]">
                                    </td>
                                    <td>
                                        <input type="number" class="form-control form-control-sm debit-input" name="items[0][debit]" step="0.01" min="0" onchange="calculateTotals()">
                                    </td>
                                    <td>
                                        <input type="number" class="form-control form-control-sm credit-input" name="items[0][credit]" step="0.01" min="0" onchange="calculateTotals()">
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-danger" onclick="removeJournalItemRow(this)">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <th colspan="2" class="text-end">Totals:</th>
                                    <th class="text-end" id="totalDebit">0</th>
                                    <th class="text-end" id="totalCredit">0</th>
                                    <th></th>
                                </tr>
                                <tr>
                                    <td colspan="5" class="text-end" id="balanceStatus"></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="addJournalItemRow()">
                        <i class="fas fa-plus me-2"></i>Add Item
                    </button>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Journal Entry</button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- Template Selection Modal --}}
<div class="modal fade" id="journalTemplateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create from Template</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Select Template</label>
                    <select class="form-select" id="templateSelect">
                        <option value="">Choose a template...</option>
                        @foreach($templates ?? [] as $code => $name)
                            <option value="{{ $code }}">{{ $code }} - {{ $name }}</option>
                        @endforeach
                    </select>
                </div>
                <div id="templateFields" style="display: none;">
                    {{-- Dynamic fields will be loaded here --}}
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="createFromTemplate()">Create Entry</button>
            </div>
        </div>
    </div>
</div>

{{-- View Journal Entry Modal --}}
<div class="modal fade" id="viewJournalModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Journal Entry Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="viewJournalContent">
                {{-- Content loaded dynamically --}}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
    function openJournalModal() {
        $('#journalForm')[0].reset();
        $('#journalId').val('');
        $('#journalItems').empty();
        addJournalItemRow();
        $('#journalModalTitle').text('Create Journal Entry');
        $('#journalModal').modal('show');
    }
    
    function openJournalTemplateModal() {
        $('#templateSelect').val('');
        $('#templateFields').hide().empty();
        $('#journalTemplateModal').modal('show');
    }
    
    $('#templateSelect').on('change', function() {
        const templateId = $(this).val();
        if (templateId) {
            // Load template fields dynamically
            $.ajax({
                url: `/accounting/templates/${templateId}/fields`,
                success: function(response) {
                    $('#templateFields').html(response).show();
                }
            });
        } else {
            $('#templateFields').hide().empty();
        }
    });
    
    function createFromTemplate() {
        const templateId = $('#templateSelect').val();
        if (!templateId) {
            showToast('Please select a template', 'warning');
            return;
        }
        
        // Collect template data
        const data = {};
        $('#templateFields input, #templateFields select').each(function() {
            data[$(this).attr('name')] = $(this).val();
        });
        
        $.ajax({
            url: `/accounting/journal-entries/template/${templateId}`,
            type: 'POST',
            data: data,
            success: function(response) {
                $('#journalTemplateModal').modal('hide');
                showToast('Journal entry created successfully', 'success');
                setTimeout(() => location.reload(), 1500);
            },
            error: function(xhr) {
                showToast(xhr.responseJSON?.message || 'Error creating entry', 'error');
            }
        });
    }
    
    $('#journalForm').on('submit', function(e) {
        e.preventDefault();
        
        const journalId = $('#journalId').val();
        const url = journalId ? `/accounting/journal-entries/${journalId}` : '{{ route("accounting.journal-entries.store") }}';
        const method = journalId ? 'PUT' : 'POST';
        
        // Validate balanced entry
        const totalDebit = parseFloat($('#totalDebit').text().replace(/,/g, '')) || 0;
        const totalCredit = parseFloat($('#totalCredit').text().replace(/,/g, '')) || 0;
        
        if (Math.abs(totalDebit - totalCredit) > 0.01) {
            showToast('Total debits must equal total credits', 'error');
            return;
        }
        
        $.ajax({
            url: url,
            type: method,
            data: $(this).serialize(),
            success: function(response) {
                $('#journalModal').modal('hide');
                showToast(journalId ? 'Journal entry updated successfully' : 'Journal entry created successfully', 'success');
                setTimeout(() => location.reload(), 1500);
            },
            error: function(xhr) {
                showToast(xhr.responseJSON?.message || 'Error saving journal entry', 'error');
            }
        });
    });
</script>