@extends('layouts.app')
@section('title', 'Cheque Books')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item">Listing</li>
    <li class="breadcrumb-item active">Cheque Books</li>
@endsection

@section('content')
@if(session('success'))
<div class="alert alert-success alert-dismissible d-flex gap-2 mb-3" style="font-size:13.5px">
    <i class="bi bi-check-circle flex-shrink-0"></i><div>{{ session('success') }}</div>
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
</div>
@endif
@if($errors->any())
<div class="alert alert-danger alert-dismissible mb-3">
    @foreach($errors->all() as $error)<div>{{ $error }}</div>@endforeach
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
@endif

<div class="page-header flex-wrap gap-3">
    <div>
        <h1 class="page-title">Cheque Books</h1>
        <p class="page-subtitle">Register each physical cheque book here.</p>
    </div>
    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#chequeBookModal"
            {{ $bankAccounts->isEmpty() ? 'disabled' : '' }}>
        <i class="bi bi-plus-lg me-1"></i>New Cheque Book
    </button>
</div>

@if($bankAccounts->isEmpty())
<div class="alert alert-warning mb-3" style="font-size:13.5px">
    No Bank Account ledgers found. Tag a chart of accounts ledger as <strong>Bank Account</strong> under the Bank section first.
</div>
@endif

<div class="card">
    <div class="card-header fw-semibold">Cheque Books</div>
    <div class="card-body p-0">
        @if($books->isEmpty())
            <div class="text-center text-muted py-5 px-3">
                No cheque books yet. Create one to begin.
            </div>
        @else
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Bank Account</th>
                            <th>Bank</th>
                            <th>Branch</th>
                            <th>Short A/C No</th>
                            <th>Book No</th>
                            <th>Leaf Range</th>
                            <th class="text-end">Leaves</th>
                            <th class="text-end pe-3" style="width:120px">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($books as $book)
                        <tr>
                            <td class="fw-semibold">
                                {{ $book->account?->code ? $book->account->code . ' ' : '' }}{{ $book->account?->name ?? '—' }}
                            </td>
                            <td>{{ $book->bank }}</td>
                            <td class="text-muted">{{ $book->branch ?: '—' }}</td>
                            <td class="text-muted">{{ $book->short_account_no ?: '—' }}</td>
                            <td>{{ $book->book_no }}</td>
                            <td>{{ $book->leafRangeLabel() }}</td>
                            <td class="text-end">{{ $book->total_leaves }}</td>
                            <td class="text-end pe-2">
                                <div class="d-flex justify-content-end gap-1">
                                    <button type="button"
                                            class="btn btn-outline-primary btn-sm edit-cheque-book"
                                            title="Edit"
                                            data-bs-toggle="modal"
                                            data-bs-target="#chequeBookModal"
                                            data-action="{{ route('banking.cheque-books.update', $book) }}"
                                            data-account-id="{{ $book->account_id }}"
                                            data-bank="{{ $book->bank }}"
                                            data-branch="{{ $book->branch }}"
                                            data-short-account-no="{{ $book->short_account_no }}"
                                            data-book-no="{{ $book->book_no }}"
                                            data-leaf-start="{{ $book->leaf_start }}"
                                            data-leaf-end="{{ $book->leaf_end }}">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <form method="POST"
                                          action="{{ route('banking.cheque-books.destroy', $book) }}"
                                          onsubmit="return confirm('Delete cheque book {{ $book->book_no }} for {{ $book->bank }}?');">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="btn btn-outline-danger btn-sm" title="Delete">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif
    </div>
</div>

<div class="modal fade" id="chequeBookModal" tabindex="-1" aria-labelledby="chequeBookModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <form method="POST" action="{{ route('banking.cheque-books.store') }}" id="chequeBookForm">
                @csrf
                <input type="hidden" name="_method" id="chequeBookMethod" value="POST">
                <div class="modal-header">
                    <h5 class="modal-title" id="chequeBookModalLabel">New Cheque Book</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-semibold" for="accountId">Bank Account</label>
                        <select name="account_id" id="accountId" class="form-select @error('account_id') is-invalid @enderror" required>
                            <option value="">Select bank account</option>
                            @foreach($bankAccounts as $account)
                                <option value="{{ $account->id }}"
                                    {{ (string) old('account_id') === (string) $account->id ? 'selected' : '' }}>
                                    {{ $account->code ? $account->code . ' — ' : '' }}{{ $account->name }}
                                </option>
                            @endforeach
                        </select>
                        @error('account_id')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold" for="bankName">Bank <span class="text-danger">*</span></label>
                            <input type="text" name="bank" id="bankName"
                                   class="form-control @error('bank') is-invalid @enderror"
                                   value="{{ old('bank') }}" required maxlength="100" placeholder="e.g. DBBL">
                            @error('bank')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold" for="branchName">Branch</label>
                            <input type="text" name="branch" id="branchName"
                                   class="form-control @error('branch') is-invalid @enderror"
                                   value="{{ old('branch') }}" maxlength="100" placeholder="e.g. Gulshan Branch">
                            @error('branch')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold" for="shortAccountNo">Short Account No</label>
                            <input type="text" name="short_account_no" id="shortAccountNo"
                                   class="form-control @error('short_account_no') is-invalid @enderror"
                                   value="{{ old('short_account_no') }}" maxlength="50" placeholder="e.g. 9876">
                            @error('short_account_no')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold" for="bookNo">Book No <span class="text-danger">*</span></label>
                            <input type="text" name="book_no" id="bookNo"
                                   class="form-control @error('book_no') is-invalid @enderror"
                                   value="{{ old('book_no') }}" required maxlength="50" placeholder="e.g. 1">
                            @error('book_no')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold" for="leafStart">Leaf Start <span class="text-danger">*</span></label>
                            <input type="number" name="leaf_start" id="leafStart"
                                   class="form-control @error('leaf_start') is-invalid @enderror"
                                   value="{{ old('leaf_start', '1') }}" required min="1" step="1">
                            @error('leaf_start')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold" for="leafEnd">Leaf End <span class="text-danger">*</span></label>
                            <input type="number" name="leaf_end" id="leafEnd"
                                   class="form-control @error('leaf_end') is-invalid @enderror"
                                   value="{{ old('leaf_end', '50') }}" required min="1" step="1">
                            @error('leaf_end')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold" for="totalLeaves">Total Leaves</label>
                            <input type="text" id="totalLeaves" class="form-control" value="50" readonly>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
(function () {
    const modal = document.getElementById('chequeBookModal');
    const form = document.getElementById('chequeBookForm');
    const methodInput = document.getElementById('chequeBookMethod');
    const title = document.getElementById('chequeBookModalLabel');
    const leafStart = document.getElementById('leafStart');
    const leafEnd = document.getElementById('leafEnd');
    const totalLeaves = document.getElementById('totalLeaves');
    const accountSelect = document.getElementById('accountId');
    const bankInput = document.getElementById('bankName');

    function updateTotalLeaves() {
        const start = parseInt(leafStart.value, 10) || 0;
        const end = parseInt(leafEnd.value, 10) || 0;
        const total = end >= start && start > 0 ? end - start + 1 : 0;
        totalLeaves.value = total > 0 ? String(total) : '';
    }

    function resetForm() {
        form.action = @json(route('banking.cheque-books.store'));
        methodInput.value = 'POST';
        title.textContent = 'New Cheque Book';
        form.reset();
        leafStart.value = '1';
        leafEnd.value = '50';
        updateTotalLeaves();
    }

    function fillFromAccount() {
        const selected = accountSelect.options[accountSelect.selectedIndex];
        if (!selected || !selected.value || bankInput.value.trim() !== '') {
            return;
        }
        const label = selected.textContent.trim();
        const name = label.includes('—') ? label.split('—').pop().trim() : label;
        bankInput.value = name;
    }

    leafStart.addEventListener('input', updateTotalLeaves);
    leafEnd.addEventListener('input', updateTotalLeaves);
    accountSelect.addEventListener('change', fillFromAccount);

    document.querySelectorAll('.edit-cheque-book').forEach(function (button) {
        button.addEventListener('click', function () {
            form.action = button.dataset.action;
            methodInput.value = 'PUT';
            title.textContent = 'Edit Cheque Book';
            accountSelect.value = button.dataset.accountId || '';
            bankInput.value = button.dataset.bank || '';
            document.getElementById('branchName').value = button.dataset.branch || '';
            document.getElementById('shortAccountNo').value = button.dataset.shortAccountNo || '';
            document.getElementById('bookNo').value = button.dataset.bookNo || '';
            leafStart.value = button.dataset.leafStart || '1';
            leafEnd.value = button.dataset.leafEnd || '1';
            updateTotalLeaves();
        });
    });

    if (modal) {
        modal.addEventListener('hidden.bs.modal', resetForm);
    }

    updateTotalLeaves();

    @if($errors->any())
    if (modal) {
        const instance = bootstrap.Modal.getOrCreateInstance(modal);
        instance.show();
        @if(old('_method') === 'PUT')
        title.textContent = 'Edit Cheque Book';
        @endif
    }
    @endif
})();
</script>
@endpush
