@extends('layouts.app')
@section('title', 'Issued & Void Cheques')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item">Transactions</li>
    <li class="breadcrumb-item active">Issued & Void Cheques</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(session('error'))
<div class="alert alert-danger alert-dismissible mb-3">{{ session('error') }}<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
@endif

@php
    $queryString = http_build_query($exportQuery ?? request()->query());
    $printUrl = route('banking.issued-void-cheques.print') . ($queryString ? '?' . $queryString : '');
    $exportUrl = route('banking.issued-void-cheques.export') . ($queryString ? '?' . $queryString : '');
@endphp

<div class="page-header flex-wrap gap-3">
    <div>
        <p class="text-uppercase text-primary fw-semibold mb-1" style="font-size:11px;letter-spacing:.08em">Transactions</p>
        <h1 class="page-title mb-1">Issued &amp; Void Cheques</h1>
        <p class="page-subtitle mb-0">All issued cheques from posted Bank Payment and Contra vouchers.</p>
    </div>
</div>

<div class="card mb-3 voucher-list-filters-card">
    <div class="card-body py-3">
        <form method="GET" action="{{ route('banking.issued-void-cheques.index') }}">
            <div class="row g-3 align-items-end">
                @include('partials.report-date-range-fields', [
                    'dateFrom' => $filters['date_from'] ?? '',
                    'dateTo' => $filters['date_to'] ?? '',
                ])
                <div class="col-6 col-md-4 col-xl-2">
                    <label class="form-label fw-semibold">Bank</label>
                    <select name="bank" class="form-select">
                        <option value="">All banks</option>
                        @foreach($filterOptions['banks'] as $bank)
                            <option value="{{ $bank }}" {{ $filters['bank'] === $bank ? 'selected' : '' }}>{{ $bank }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <label class="form-label fw-semibold">Bank A/C No</label>
                    <select name="bank_account_no" class="form-select">
                        <option value="">All accounts</option>
                        @foreach($filterOptions['account_nos'] as $accountNo)
                            <option value="{{ $accountNo }}" {{ $filters['bank_account_no'] === $accountNo ? 'selected' : '' }}>{{ $accountNo }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <label class="form-label fw-semibold">Branch</label>
                    <select name="branch" class="form-select">
                        <option value="">All branches</option>
                        @foreach($filterOptions['branches'] as $branch)
                            <option value="{{ $branch }}" {{ $filters['branch'] === $branch ? 'selected' : '' }}>{{ $branch }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <label class="form-label fw-semibold">Book No</label>
                    <select name="book_no" class="form-select">
                        <option value="">All books</option>
                        @foreach($filterOptions['book_nos'] as $bookNo)
                            <option value="{{ $bookNo }}" {{ $filters['book_no'] === $bookNo ? 'selected' : '' }}>{{ $bookNo }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <label class="form-label fw-semibold">Payee</label>
                    @include('accounting.vouchers._list_party_filter', [
                        'filterOptions' => $filterOptions,
                        'filters' => $filters,
                        'selectedPartyLabel' => $selectedPartyLabel ?? 'All names',
                    ])
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <label class="form-label fw-semibold">Status</label>
                    <select name="status" class="form-select">
                        @foreach($filterOptions['statuses'] as $value => $label)
                            <option value="{{ $value }}" {{ $filters['status'] === (string) $value ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <label class="form-label fw-semibold">Columns by</label>
                    @include('reports.profit-loss._multi-filter-picker', [
                        'pickerId' => 'ivcColumnsPicker',
                        'emptyLabel' => 'All columns',
                        'searchPlaceholder' => 'Search columns...',
                        'inputName' => 'columns[]',
                        'selectedValues' => $filters['columns'] ?? [],
                        'options' => $filterOptions['columns'],
                        'toggleLabel' => $selectedColumnsLabel ?? 'All columns',
                    ])
                </div>
                <div class="col-6 col-md-4 col-xl-2">
                    <label class="form-label fw-semibold">Sort By</label>
                    <select name="sort" class="form-select">
                        @foreach($filterOptions['sortOptions'] as $value => $label)
                            <option value="{{ $value }}" {{ ($filters['sort'] ?? '') === (string) $value ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-12 col-md-6 col-xl-4">
                    <label class="form-label fw-semibold">Search</label>
                    <input type="text" name="search" class="form-control"
                           value="{{ $filters['search'] ?? '' }}"
                           placeholder="Voucher no., cheque no., payee, reference…">
                </div>
                <div class="col-12 col-xl-auto d-flex flex-wrap gap-2">
                    <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-funnel me-1"></i>Apply</button>
                    <a href="{{ route('banking.issued-void-cheques.index') }}" class="btn btn-outline-secondary btn-sm">Reset</a>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header fw-semibold d-flex flex-wrap align-items-center justify-content-between gap-2">
        <span>Cheque Transactions</span>
        <div class="d-flex flex-wrap gap-2">
            <a href="{{ $exportUrl }}" class="btn btn-outline-success btn-sm"><i class="bi bi-file-earmark-excel me-1"></i>Excel</a>
            <a href="{{ $printUrl }}" target="_blank" class="btn btn-outline-secondary btn-sm"><i class="bi bi-printer me-1"></i>Print</a>
            <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#ivcEmailModal">
                <i class="bi bi-envelope me-1"></i>Email
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        @include('banking.issued-void-cheques._table', [
            'showActions' => true,
            'linkVoucher' => true,
            'formats' => $formats,
        ])
    </div>
    @if($rows->hasPages())
    <div class="card-footer">{{ $rows->links() }}</div>
    @endif
</div>

<div class="modal fade" id="printChequeModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="POST" id="printChequeForm" action="" target="_blank">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title">Print Cheque</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="text-muted mb-3" style="font-size:13px">Cheque No: <strong id="printChequeNoLabel">—</strong></p>
                    <label class="form-label fw-semibold" for="printChequeFormatId">Cheque Format</label>
                    <select name="cheque_format_id" id="printChequeFormatId" class="form-select" required>
                        @foreach($formats as $format)
                            <option value="{{ $format->id }}">{{ $format->name }}</option>
                        @endforeach
                    </select>
                </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"><i class="bi bi-printer me-1"></i>Print</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('styles')
@include('partials.report-datepicker-assets')
@endpush

@push('modals')
<div class="modal fade" id="ivcEmailModal" tabindex="-1" aria-labelledby="ivcEmailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="POST" action="{{ route('banking.issued-void-cheques.email', $exportQuery ?? request()->query()) }}">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title" id="ivcEmailModalLabel">Email Issued &amp; Void Cheques</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 d-block">Attachment Format</label>
                        <div class="btn-group w-100" role="group">
                            <input type="radio" class="btn-check" name="format" id="ivcEmailPdf" value="pdf" checked>
                            <label class="btn btn-outline-primary" for="ivcEmailPdf"><i class="bi bi-file-earmark-pdf me-1"></i>PDF</label>
                            <input type="radio" class="btn-check" name="format" id="ivcEmailXlsx" value="xlsx">
                            <label class="btn btn-outline-primary" for="ivcEmailXlsx"><i class="bi bi-file-earmark-excel me-1"></i>Excel</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Recipient Email</label>
                        <input type="email" name="recipient" class="form-control" value="{{ auth()->user()->email }}" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Subject</label>
                        <input type="text" name="subject" class="form-control" value="Issued & Void Cheques — {{ auth()->user()->company?->name }}">
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-semibold">Message</label>
                        <textarea name="message" class="form-control" rows="4">Please find the attached Issued & Void Cheques report.

{{ $filterSummary }}</textarea>
                    </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"><i class="bi bi-send me-1"></i>Send Email</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endpush

@push('scripts')
@include('partials.report-datepicker-init')
<script src="{{ asset('js/voucher-list-filters.js') }}?v={{ filemtime(public_path('js/voucher-list-filters.js')) }}" defer></script>
<script>
(function () {
    const printForm = document.getElementById('printChequeForm');
    const printLabel = document.getElementById('printChequeNoLabel');
    const printBaseUrl = @json(rtrim(route('banking.issued-void-cheques.index'), '/'));

    document.querySelectorAll('.print-cheque-action').forEach(function (button) {
        button.addEventListener('click', function () {
            const voucherId = button.dataset.voucherId;
            if (printForm) {
                printForm.action = printBaseUrl + '/' + voucherId + '/print-cheque';
            }
            if (printLabel) {
                printLabel.textContent = button.dataset.chequeNo || '—';
            }
        });
    });
})();
</script>
@endpush
