@extends('layouts.master')
@section('content')
<div class="container-fluid py-3">
    <div class="d-flex justify-content-end mb-3">
        <a href="{{ route('home') }}" class="btn-back">
            <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
        </a>
    </div>

    <div class="row">
        <!-- Form Section -->
        <div class="col-lg-4">
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-primary text-white py-3">
                    <h5 class="mb-0" id="formTitle"><i class="fas fa-book me-2"></i> Process Supplier Journal</h5>
                </div>
                <div class="card-body">
                    <form action="{{ route('supplier.journal.store') }}" method="POST" novalidate id="journalForm">
                        @csrf
                        <input type="hidden" name="id" id="entryId" value="">

                        <div id="timeout">
                            @if(Session::has('success'))
                                <p class="alert alert-info">{{ Session('success') }}</p>
                            @endif
                            @if(Session::has('error'))
                                <p class="alert alert-danger">{{ Session('error') }}</p>
                            @endif
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Account Code:</strong></label>
                            <input type="text" class="form-control" value="{{ $supplierAccount->code ?? '9600' }}" disabled>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Date:</strong></label>
                            <input type="date" name="date" class="form-control" id="date" value="{{ old('date', date('Y-m-d')) }}" required />
                            @error('date')<div class="text-danger small">{{ $message }}</div>@enderror
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Narration:</strong></label>
                            <input class="form-control" type="text" name="narration" id="narration" value="{{ old('narration') }}" placeholder="Enter narration" required />
                            @error('narration')<div class="text-danger small">{{ $message }}</div>@enderror
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Supplier Account:</strong></label>
                            <select name="supplier_account_id" id="supplier_account_id" class="form-control" required>
                                <option value="">Select Supplier Account</option>
                                @foreach($suppliers as $supplier)
                                    <option value="{{ $supplier->id }}" {{ old('supplier_account_id') == $supplier->id ? 'selected' : '' }}>
                                        {{ $supplier->supplier_code }} - {{ $supplier->supplier_account }}
                                    </option>
                                @endforeach
                            </select>
                            @error('supplier_account_id')<div class="text-danger small">{{ $message }}</div>@enderror
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Reference:</strong></label>
                            <input class="form-control" type="text" name="reference" id="reference" value="{{ old('reference') }}" placeholder="Enter reference" required />
                            @error('reference')<div class="text-danger small">{{ $message }}</div>@enderror
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>TR Code:</strong></label>
                            <select name="tr_code" id="tr_code" class="form-control" required>
                                <option value="">Select TR Code</option>
                                <option value="DR" {{ old('tr_code') == 'DR' ? 'selected' : '' }}>DR</option>
                                <option value="CR" {{ old('tr_code') == 'CR' ? 'selected' : '' }}>CR</option>
                            </select>
                            @error('tr_code')<div class="text-danger small">{{ $message }}</div>@enderror
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Currency:</strong></label>
                            <select name="currency_id" id="currency_id" class="form-control" required>
                                <option value="">Select Currency</option>
                                @foreach($currencies as $currency)
                                    <option value="{{ $currency->id }}" {{ old('currency_id') == $currency->id ? 'selected' : '' }}>
                                        {{ $currency->code }} - {{ $currency->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('currency_id')<div class="text-danger small">{{ $message }}</div>@enderror
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Amount:</strong></label>
                            <input class="form-control" type="number" step="0.01" name="amount" id="amount" value="{{ old('amount') }}" placeholder="00.00" required />
                            @error('amount')<div class="text-danger small">{{ $message }}</div>@enderror
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Project:</strong></label>
                            <select name="project_id" class="form-control" id="project_id" required>
                                <option value="">Select Project (Optional)</option>
                                @foreach($projects as $project)
                                            <option value="{{ $project->id }}" {{ old('project_id') == $project->id ? 'selected' : '' }}>
                                                {{ $project->code }} - {{ $project->name }}
                                            </option>
                                        @endforeach
                            </select>
                            @error('project_id')
                                <small class="text-danger">{{ $message }}</small>
                            @enderror
                        </div>

                        <div class="d-flex justify-content-end mt-4">
                            <button type="submit" id="submitButton" class="btn btn-primary me-2">Save</button>
                            <button type="reset" class="btn btn-outline-secondary" id="resetButton">Refresh</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Table Section -->
        <div class="col-lg-8 mt-4 mt-lg-0">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-list me-2"></i> Journal Entries</h5>
                    @if($tempEntries->isNotEmpty())
                        <form action="{{ route('supplier.journal.processAll') }}" method="POST" class="m-0">
                            @csrf
                            <button type="submit" id="processJournalBtn" class="btn btn-success btn-sm">PROCESS ALL</button>
                        </form>
                    @endif
                </div>
                <div class="card-body">
                    @if($tempEntries->isEmpty())
                        <p class="text-muted mb-0">No journal entries available.</p>
                    @else
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>Date</th>
                                        <th>Supplier Code</th>
                                        <th>Supplier Name</th> 
                                        <th>Narration</th>
                                        <th>DR</th>
                                        <th>CR</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($tempEntries as $entry)
                                    <tr>
                                        <td>{{ date('d/m/Y', strtotime($entry->date)) }}</td>
                                        <td>{{ $entry->supplier->supplier_code }}</td>
                                        <td>{{ $entry->supplier->supplier_account }}</td>
                                        <td>{{ $entry->narration }}</td>
                                        <td>{{ $entry->tr_code === 'DR' ? number_format($entry->amount, 2) : '' }}</td>
                                        <td>{{ $entry->tr_code === 'CR' ? number_format($entry->amount, 2) : '' }}</td>
                                        <td>
                                            @if($entry->status === 'Processed')
                                                <span class="badge bg-success">Processed</span>
                                            @else
                                                <span class="badge bg-warning text-dark">Open Journal</span>
                                            @endif
                                        </td>
                                        <td class="text-center">
                                            <a href="#" class="btn btn-sm btn-primary" onclick="editEntry({{ $entry->id }})">
                                                <i class="fas fa-edit"></i>
                                            </a>

                                            <!-- Process single entry -->
                                            @if($entry->status !== 'Processed')
                                            <form action="{{ route('supplier.journal.processSingle', $entry->id) }}" method="POST" class="d-inline">
                                                @csrf
                                                <button type="submit" class="btn btn-sm btn-success process-btn">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                            </form>
                                            @endif

                                            <!-- Delete button triggers modal -->
                                            <button class="btn btn-sm btn-danger deleteBtn" data-id="{{ $entry->id }}">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" id="deleteForm">
            @csrf
            @method('DELETE')
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">Confirm Deletion</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">Are you sure you want to delete this journal entry?</div>
                <div class="modal-footer">
                    <button id="cancelDeleteBtn" type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button id="confirmDeleteBtn" type="submit" class="btn btn-danger">Delete</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const bsModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
        const deleteForm = document.getElementById('deleteForm');

        document.querySelectorAll('.deleteBtn').forEach(btn => {
            btn.addEventListener('click', function (e) {
                e.preventDefault();
                const entryId = this.getAttribute('data-id');
                const url = '{{ url("supplier-journal/delete") }}/' + entryId;
                deleteForm.setAttribute('action', url);
                bsModal.show();
            });
        });
    });

    function editEntry(id) {
        const entry = @json($tempEntries->keyBy('id'));
        const selected = entry[id];
        if (!selected) {
            alert('Entry data not found');
            return;
        }

        document.getElementById('entryId').value = selected.id;
        document.getElementById('date').value = selected.date;
        document.getElementById('narration').value = selected.narration;
        document.getElementById('supplier_account_id').value = selected.supplier_account_id;
        document.getElementById('reference').value = selected.reference;
        document.getElementById('tr_code').value = selected.tr_code;
        document.getElementById('currency_id').value = selected.currency_id;
        document.getElementById('amount').value = selected.amount;

        document.getElementById('formTitle').innerHTML = '<i class="fas fa-book me-2"></i> Edit Supplier Journal Entry';
        document.getElementById('submitButton').textContent = 'Update';
        document.getElementById('journalForm').action = '{{ route("supplier.journal.update") }}';

        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    document.getElementById('resetButton').addEventListener('click', function() {
        document.getElementById('entryId').value = '';
        document.getElementById('formTitle').innerHTML = '<i class="fas fa-book me-2"></i> Process Supplier Journal';
        document.getElementById('submitButton').textContent = 'Save';
        document.getElementById('journalForm').action = '{{ route("supplier.journal.store") }}';
    });

    setTimeout(() => {
        document.querySelectorAll('.alert').forEach(alert => alert.style.display = 'none');
    }, 5000);
</script>

<style>
.btn-back {
    text-decoration: none;
    color: #1AB9D9;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    padding: 5px 15px;
    border-radius: 4px;
    transition: all 0.3s;
}
.btn-back:hover {
    background-color: rgba(26, 185, 217, 0.1);
    text-decoration: none;
}
.card {
    border-radius: 8px;
    overflow: hidden;
    border: none;
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
}
.card-header {
    border-bottom: 1px solid rgba(0,0,0,0.1);
    padding: 12px 20px;
}
.table th {
    background-color: #f8f9fa;
}
#processJournalBtn {
    background-color: #ffffff !important;
    color: #1AB9D9 !important;
    border: 1px solid rgba(26,185,217,0.35) !important;
    font-weight: 600 !important;
    padding: 7px 14px !important;
    box-shadow: none !important;
    line-height: 1 !important;
}
#processJournalBtn:hover {
    background-color: #f5fbfc !important;
    color: #1498b0 !important;
    border-color: rgba(20,152,176,0.45) !important;
}
.table .process-btn {
    background-color: #1AB9D9 !important;
    border: 1px solid rgba(26,185,217,0.35) !important;
    color: #fff !important;
}
.table .process-btn:hover {
    background-color: #1498b0 !important;
    border-color: rgba(20,152,176,0.45) !important;
}
.table-responsive {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

@media (max-width: 768px) {
    table.table {
        font-size: 0.85rem;
    }
    table.table th,
    table.table td {
        white-space: nowrap;
    }
}

.text-danger.small {
    font-size: 0.85rem;
}
</style>
@endsection
