@extends('layouts.app')
@section('title', $voucher->voucher_number ?? 'Voucher')
@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="{{ route('vouchers.index', $voucherType) }}">{{ $label }}</a></li>
    <li class="breadcrumb-item active">{{ $voucher->voucher_number }}</li>
@endsection

@push('styles')
<style>
.voucher-print-area { display:none }
@media print {
    #sidebar,#topbar,.screen-only,.modal { display:none !important }
    #main { margin-left:0 !important; padding-top:0 !important }
    body  { background:#fff !important }
    .page-content { padding:0 !important }
    .voucher-print-area { display:block !important }

    .vp { width:100%;max-width:820px;margin:0 auto;font-family:'Segoe UI',Arial,sans-serif;font-size:12px;color:#000;position:relative }
    .vp-top { display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:10px }
    .vp-logo { max-height:55px;max-width:160px;object-fit:contain }
    .vp-co-name { font-size:15px;font-weight:700;margin:0 0 2px }
    .vp-co-addr { font-size:11px;color:#333;margin:0;line-height:1.5 }
    .vp-co-contact { text-align:right;font-size:11px;color:#333 }
    .vp-title { font-size:14px;font-weight:700;text-align:center;border-bottom:2px solid #000;padding-bottom:5px;margin:10px 0 12px }
    .vp-meta { display:grid;grid-template-columns:1fr 1fr;gap:4px 24px;margin-bottom:12px }
    .vp-row { display:flex;gap:4px;font-size:12px }
    .vp-lbl { font-weight:700;min-width:100px;white-space:nowrap }
    .vp-val { border-bottom:1px dotted #bbb;flex:1;padding-bottom:1px }
    .vp-full { grid-column:1/-1 }
    .vp-table { width:100%;border-collapse:collapse;margin-bottom:10px }
    .vp-table th { background:#000;color:#fff;padding:5px 8px;border:1px solid #000;font-size:12px }
    .vp-table th.r { text-align:right }
    .vp-table td { padding:4px 8px;border:1px solid #999;font-size:12px }
    .vp-table td.r { text-align:right }
    .vp-table tr:nth-child(even) td { background:#f9f9f9 }
    .vp-table tfoot td { font-weight:700;border-top:2px solid #000;padding:5px 8px }
    .vp-words { font-size:11.5px;margin:6px 0 20px }
    .vp-sigs { display:flex;gap:20px;margin-top:40px }
    .vp-sig { flex:1;text-align:center }
    .vp-sig-line { border-top:1px solid #000;padding-top:4px;font-size:11.5px;font-weight:600;margin-top:28px }
    .vp-stamp { position:absolute;top:80px;right:30px;border:3px solid;border-radius:4px;padding:4px 14px;font-size:20px;font-weight:900;transform:rotate(-15deg);opacity:.3;text-transform:uppercase }
}
</style>
@endpush

@section('content')
@php
    [$sbg,$sfg] = $voucher->getStatusColor();
    $user        = auth()->user();
    $totalDebit  = $voucher->lines->where('dr_cr','dr')->sum('line_total');
    $totalCredit = $voucher->lines->where('dr_cr','cr')->sum('line_total');
    $isBalanced  = abs($totalDebit - $totalCredit) < 0.01;
    $extraData   = $voucher->extra_data ?? [];
    $chequeNo    = $extraData['cheque_no']   ?? '';
    $chequeDate  = $extraData['cheque_date'] ?? '';
    $paymentMethodLabel = \App\Support\VoucherPaymentMethods::label($extraData['payment_method'] ?? null);
    $partyName  = $partyName  ?? null;
    $partyLabel = $partyLabel ?? null;
    $company    = $company    ?? auth()->user()->company;
    $settings   = $settings   ?? array_merge(\App\Models\Setting::defaults(), \App\Models\Setting::where('company_id', auth()->user()->company_id)->get()->pluck('value','key')->toArray());

    // Signatories from settings
    $sig1 = $settings['signatory_prepared_by'] ?? 'Prepared By';
    $sig2 = $settings['signatory_checked_by']  ?? 'Checked By';
    $sig3 = $settings['signatory_custom1']      ?? '';
    $sig4 = $settings['signatory_custom2']      ?? '';
    $sig5 = $settings['signatory_approved_by']  ?? 'Approved By';

    // Currency-aware Amount in Words
    $grandTotal = (float) ($voucher->grand_total ?? max($totalDebit, $totalCredit));
    $amountInWords = \App\Helpers\NumberHelper::amountInWordsForCompany($grandTotal, auth()->user()->company_id);

    // Voucher title — always append "Voucher"
    $printTitle = $label . ' Voucher';

    // Party label on screen
    $screenPartyLabel = match($voucherType) {
        'cash_payment','bank_payment' => 'Paid To',
        'cash_receipt','bank_receipt' => 'Received From',
        default => null,
    };
@endphp

{{-- ════════════════════════════════════════════════════════════ --}}
{{-- SCREEN VIEW                                                   --}}
{{-- ════════════════════════════════════════════════════════════ --}}
<div class="screen-only">

<div class="page-header flex-wrap gap-3">
    <div class="d-flex align-items-center gap-2 flex-wrap">
        <div>
            <h1 class="page-title mb-0">{{ $voucher->voucher_number }}</h1>
            <p class="page-subtitle mb-0">{{ $printTitle }} — {{ $voucher->voucher_date->format('d M Y') }}</p>
        </div>
        <span class="badge px-3 py-2" style="background:{{ $sbg }};color:{{ $sfg }};font-size:13px">
            {{ ucfirst($voucher->status) }}
        </span>
        @if($isReversed)
        <span class="badge px-3 py-2" style="background:#f8d7da;color:#842029;font-size:12px">
            <i class="bi bi-arrow-repeat me-1"></i>Reversed
        </span>
        @endif
    </div>
    <div class="d-flex gap-2 align-items-center flex-wrap">
        <button type="button" class="btn btn-primary btn-sm" onclick="window.print()">
            <i class="bi bi-printer me-1"></i>Print Voucher
        </button>
        @if($user->hasPermission('vouchers','edit'))
        <a href="{{ route('vouchers.edit',[$voucherType,$voucher]) }}" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-pencil me-1"></i>Edit
        </a>
        @endif
        @if($approvalReq && ($voucher->isDraft() || $voucher->isSubmitted()) && $user->hasPermission('vouchers','approve'))
        <button class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#approveModal"><i class="bi bi-check-circle me-1"></i>Approve</button>
        @endif
        @if($voucher->isPosted() && !$isReversed && $user->hasPermission('vouchers','post'))
        <button class="btn btn-outline-warning btn-sm" data-bs-toggle="modal" data-bs-target="#reverseModal"><i class="bi bi-arrow-repeat me-1"></i>Reverse</button>
        @endif
        @if(!$voucher->isPosted() && !$voucher->isCancelled() && $user->hasPermission('vouchers','cancel'))
        <button class="btn btn-outline-danger btn-sm" data-bs-toggle="modal" data-bs-target="#cancelModal"><i class="bi bi-ban me-1"></i>Cancel</button>
        @endif
    </div>
</div>

<div class="row g-4">
    <div class="col-12 col-xl-8">
        <div class="card mb-4">
            <div class="card-header fw-semibold"><i class="bi bi-info-circle me-2 text-primary"></i>Voucher Details</div>
            <div class="card-body">
                <div class="row g-3" style="font-size:13.5px">
                    <div class="col-6 col-md-3"><div class="text-muted mb-1" style="font-size:12px">Voucher No</div><div class="fw-semibold">{{ $voucher->voucher_number }}</div></div>
                    <div class="col-6 col-md-3"><div class="text-muted mb-1" style="font-size:12px">Date</div><div class="fw-semibold">{{ $voucher->voucher_date->format('d M Y') }}</div></div>
                    @if($chequeNo)
                    <div class="col-6 col-md-3"><div class="text-muted mb-1" style="font-size:12px">Cheque No</div><div class="fw-semibold">{{ $chequeNo }}</div></div>
                    @endif
                    @if($chequeDate)
                    <div class="col-6 col-md-3"><div class="text-muted mb-1" style="font-size:12px">Cheque Date</div><div class="fw-semibold">{{ \Carbon\Carbon::parse($chequeDate)->format('d M Y') }}</div></div>
                    @endif
                    @if($paymentMethodLabel)
                    <div class="col-6 col-md-3"><div class="text-muted mb-1" style="font-size:12px">Payment Method</div><div class="fw-semibold">{{ $paymentMethodLabel }}</div></div>
                    @endif
                    @if($partyName && $screenPartyLabel)
                    <div class="col-6 col-md-3">
                        <div class="text-muted mb-1" style="font-size:12px">{{ $screenPartyLabel }}</div>
                        <div class="fw-semibold">{{ $partyName }}</div>
                        <div class="text-muted" style="font-size:11.5px">{{ ucfirst(str_replace('_',' ',$voucher->party_type??'')) }}</div>
                    </div>
                    @endif
                    @if($voucher->reference)
                    <div class="col-6 col-md-3"><div class="text-muted mb-1" style="font-size:12px">Reference</div><div>{{ $voucher->reference }}</div></div>
                    @endif
                    @if($voucher->narration)
                    <div class="col-12"><div class="text-muted mb-1" style="font-size:12px">Narration</div><div>{{ $voucher->narration }}</div></div>
                    @endif
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header fw-semibold"><i class="bi bi-table me-2 text-primary"></i>Account Lines</div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table mb-0" style="font-size:13.5px">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-3">#</th>
                                <th>Account</th>
                                <th class="d-none d-md-table-cell">Description</th>
                                <th class="text-end" style="color:#198754">Debit</th>
                                <th class="text-end" style="color:#dc3545">Credit</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($voucher->lines as $i => $line)
                            <tr>
                                <td class="ps-3 text-muted">{{ $i+1 }}</td>
                                <td>
                                    <div class="fw-semibold">{{ $line->account->name ?? '—' }}</div>
                                    @if($line->account->code ?? false)<div class="text-muted" style="font-size:12px">{{ $line->account->code }}</div>@endif
                                </td>
                                <td class="d-none d-md-table-cell text-muted">{{ $line->description ?? '' }}</td>
                                <td class="text-end fw-semibold" style="color:#198754">{{ $line->dr_cr==='dr' ? number_format($line->line_total,2) : '' }}</td>
                                <td class="text-end fw-semibold" style="color:#dc3545">{{ $line->dr_cr==='cr' ? number_format($line->line_total,2) : '' }}</td>
                            </tr>
                            @endforeach
                        </tbody>
                        <tfoot class="table-light">
                            <tr>
                                <td colspan="3" class="ps-3 fw-bold">Total</td>
                                <td class="text-end fw-bold" style="color:#198754">{{ number_format($totalDebit,2) }}</td>
                                <td class="text-end fw-bold" style="color:#dc3545">{{ number_format($totalCredit,2) }}</td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
            <div class="card-footer bg-white voucher-journal-footer">
                <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
                    <div style="font-size:13px">
                        <span class="text-muted me-2">Amount in Words:</span>
                        <span class="fw-semibold text-primary">{{ $amountInWords }}</span>
                    </div>
                    <span class="badge px-3 py-2" style="font-size:12px;background:{{ $isBalanced?'#d1e7dd':'#f8d7da' }};color:{{ $isBalanced?'#0a3622':'#842029' }}">
                        {{ $isBalanced ? 'Balanced' : 'Not Balanced' }}
                    </span>
                </div>
                @include('accounting.vouchers._attachments_panel', [
                    'mode' => 'show',
                    'layout' => 'inline',
                    'voucher' => $voucher,
                    'voucherType' => $voucherType,
                    'attachments' => $voucher->attachments,
                ])
            </div>
        </div>
    </div>

    <div class="col-12 col-xl-4">
        <div class="card">
            <div class="card-header fw-semibold"><i class="bi bi-clock-history me-2 text-primary"></i>Workflow</div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0" style="font-size:13px">
                    <tr><td class="text-muted ps-3 py-2">Status</td><td class="py-2"><span class="badge" style="background:{{ $sbg }};color:{{ $sfg }}">{{ ucfirst($voucher->status) }}</span></td></tr>
                    @if($voucher->createdBy)<tr><td class="text-muted ps-3 py-2">Created By</td><td class="py-2">{{ $voucher->createdBy->name }}</td></tr>@endif
                    @if($voucher->approvedBy)<tr><td class="text-muted ps-3 py-2">Approved By</td><td class="py-2">{{ $voucher->approvedBy->name }}</td></tr>@endif
                    @if($voucher->posted_at)<tr><td class="text-muted ps-3 py-2">Posted At</td><td class="py-2">{{ $voucher->posted_at->format('d M Y H:i') }}</td></tr>@endif
                </table>
            </div>
        </div>
    </div>
</div>
</div>{{-- end screen-only --}}

{{-- ════════════════════════════════════════════════════════════ --}}
{{-- PRINT AREA                                                    --}}
{{-- ════════════════════════════════════════════════════════════ --}}
<div class="voucher-print-area">
<div class="vp">

    {{-- Status stamp --}}
    @if($voucher->isCancelled())
    <div class="vp-stamp" style="color:#dc3545;border-color:#dc3545">CANCELLED</div>
    @elseif($isReversed)
    <div class="vp-stamp" style="color:#f57c00;border-color:#f57c00">REVERSED</div>
    @endif

    {{-- Company Header --}}
    <div class="vp-top">
        <div>
            @php $printLogoPath = app(\App\Support\BrandLogoManager::class)->localCompanyLogoPath($company); @endphp
            @if($printLogoPath && is_file($printLogoPath))
            <img src="{{ $printLogoPath }}" class="vp-logo logo logo--company logo--print" alt="{{ $company->name }}">
            @endif
            <p class="vp-co-name" style="{{ $printLogoPath ? 'margin-top:4px' : '' }}">{{ $company->name }}</p>
            @if($company->address)<p class="vp-co-addr">{{ $company->address }}</p>@endif
        </div>
        <div class="vp-co-contact">
            @if($company->phone)<div>Tel: {{ $company->phone }}</div>@endif
            @if($company->email)<div>{{ $company->email }}</div>@endif
            @if($company->website)<div>{{ $company->website }}</div>@endif
        </div>
    </div>

    {{-- Title: e.g. "Bank Payment Voucher" --}}
    <div class="vp-title">{{ $printTitle }}</div>

    {{-- Meta grid --}}
    <div class="vp-meta">
        @if($chequeNo)
        <div class="vp-row"><span class="vp-lbl">Check No</span><span class="vp-val">: {{ $chequeNo }}</span></div>
        @endif
        @if($paymentMethodLabel ?? null)
        <div class="vp-row"><span class="vp-lbl">Payment Method</span><span class="vp-val">: {{ $paymentMethodLabel }}</span></div>
        @endif
        <div class="vp-row"><span class="vp-lbl">Voucher No</span><span class="vp-val">: {{ $voucher->voucher_number }}</span></div>
        @if($chequeDate)
        <div class="vp-row"><span class="vp-lbl">Check Date</span><span class="vp-val">: {{ \Carbon\Carbon::parse($chequeDate)->format('d-M-y') }}</span></div>
        @endif
        <div class="vp-row"><span class="vp-lbl">Voucher Date</span><span class="vp-val">: {{ $voucher->voucher_date->format('d-M-y') }}</span></div>
        @if($partyName && $partyLabel)
        <div class="vp-row vp-full"><span class="vp-lbl">{{ $partyLabel }}</span><span class="vp-val">: {{ $partyName }}</span></div>
        @endif
        @if($voucher->reference)
        <div class="vp-row"><span class="vp-lbl">Reference</span><span class="vp-val">: {{ $voucher->reference }}</span></div>
        @endif
        @if($voucher->narration)
        <div class="vp-row vp-full"><span class="vp-lbl">Narration</span><span class="vp-val">: {{ $voucher->narration }}</span></div>
        @endif
    </div>

    {{-- Lines --}}
    <table class="vp-table">
        <thead>
            <tr>
                <th style="width:30%">Account Name &amp; Code</th>
                <th>Memo</th>
                <th class="r" style="width:13%">Debit</th>
                <th class="r" style="width:13%">Credit</th>
            </tr>
        </thead>
        <tbody>
            @foreach($voucher->lines as $line)
            <tr>
                <td>{{ $line->account->name ?? '—' }}{{ ($line->account->code ?? false) ? ' '.$line->account->code : '' }}</td>
                <td>{{ $line->description ?? '' }}</td>
                <td class="r">{{ $line->dr_cr==='dr' ? number_format($line->line_total,2) : '' }}</td>
                <td class="r">{{ $line->dr_cr==='cr' ? number_format($line->line_total,2) : '' }}</td>
            </tr>
            @endforeach
        </tbody>
        <tfoot>
            <tr>
                <td colspan="2" class="r">Total</td>
                <td class="r">{{ number_format($totalDebit,2) }}</td>
                <td class="r">{{ number_format($totalCredit,2) }}</td>
            </tr>
        </tfoot>
    </table>

    {{-- Amount in Words --}}
    <div class="vp-words">
        <strong>Amount in word :</strong>
        <span style="border-bottom:1px solid #999;padding-bottom:1px">{{ $amountInWords }}</span>
    </div>

    {{-- Signatories --}}
    <div class="vp-sigs">
        <div class="vp-sig"><div class="vp-sig-line">{{ $sig1 ?: 'Prepared By' }}</div></div>
        <div class="vp-sig"><div class="vp-sig-line">{{ $sig2 ?: 'Checked By' }}</div></div>
        @if($sig3)<div class="vp-sig"><div class="vp-sig-line">{{ $sig3 }}</div></div>@endif
        @if($sig4)<div class="vp-sig"><div class="vp-sig-line">{{ $sig4 }}</div></div>@endif
        <div class="vp-sig"><div class="vp-sig-line">{{ $sig5 ?: 'Approved By' }}</div></div>
    </div>

</div>
</div>{{-- end print --}}

{{-- Modals --}}
<div class="modal fade screen-only" id="approveModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
    <div class="modal-header border-0 pb-0"><h5 class="modal-title fw-semibold"><i class="bi bi-check-circle me-2 text-success"></i>Approve &amp; Post Voucher</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <form method="POST" action="{{ route('vouchers.approve',[$voucherType,$voucher]) }}">@csrf
    <div class="modal-body">
        <div class="rounded-2 p-3 mb-3" style="background:#f8f9fa;font-size:13.5px"><strong>{{ $voucher->voucher_number }}</strong><div class="text-muted">{{ $voucher->voucher_date->format('d M Y') }}</div></div>
        <div class="alert alert-info" style="font-size:13px">Approving this voucher will immediately post it to the ledger and update all related reports.</div>
        <label class="form-label fw-semibold">Comments <span class="text-muted fw-normal">(optional)</span></label>
        <textarea name="comments" class="form-control" rows="2" placeholder="Any notes…"></textarea>
    </div>
    <div class="modal-footer border-0 pt-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-success px-4"><i class="bi bi-check-circle me-1"></i>Approve</button></div>
    </form>
</div></div></div>

<div class="modal fade screen-only" id="rejectModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
    <div class="modal-header border-0 pb-0"><h5 class="modal-title fw-semibold"><i class="bi bi-x-circle me-2 text-warning"></i>Reject Voucher</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <form method="POST" action="{{ route('vouchers.reject',[$voucherType,$voucher]) }}">@csrf
    <div class="modal-body"><label class="form-label fw-semibold">Reason <span class="text-danger">*</span></label><textarea name="reason" class="form-control" rows="3" required placeholder="Explain the issue…"></textarea></div>
    <div class="modal-footer border-0 pt-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-warning px-4"><i class="bi bi-x-circle me-1"></i>Reject</button></div>
    </form>
</div></div></div>

<div class="modal fade screen-only" id="reverseModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
    <div class="modal-header border-0 pb-0"><h5 class="modal-title fw-semibold"><i class="bi bi-arrow-repeat me-2 text-warning"></i>Reverse Voucher</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <form method="POST" action="{{ route('vouchers.reverse',[$voucherType,$voucher]) }}">@csrf
    <div class="modal-body">
        <div class="alert alert-warning py-2 mb-3 d-flex gap-2" style="font-size:13px"><i class="bi bi-info-circle flex-shrink-0 mt-1"></i><div>A reversal voucher will be created. Original will be marked Reversed.</div></div>
        <div class="mb-3"><label class="form-label fw-semibold">Reversal Date <span class="text-danger">*</span></label><input type="date" name="reversal_date" class="form-control" value="{{ date('Y-m-d') }}" required></div>
        <div><label class="form-label fw-semibold">Reason <span class="text-danger">*</span></label><textarea name="reason" class="form-control" rows="2" required placeholder="Reason for reversal…"></textarea></div>
    </div>
    <div class="modal-footer border-0 pt-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-warning px-4"><i class="bi bi-arrow-repeat me-1"></i>Create Reversal</button></div>
    </form>
</div></div></div>

<div class="modal fade screen-only" id="cancelModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
    <div class="modal-header border-0 pb-0"><h5 class="modal-title fw-semibold"><i class="bi bi-ban me-2 text-danger"></i>Cancel Voucher</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <form method="POST" action="{{ route('vouchers.cancel',[$voucherType,$voucher]) }}">@csrf
    <div class="modal-body"><label class="form-label fw-semibold">Reason <span class="text-danger">*</span></label><textarea name="reason" class="form-control" rows="2" required placeholder="Reason for cancellation…"></textarea></div>
    <div class="modal-footer border-0 pt-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-danger px-4"><i class="bi bi-ban me-1"></i>Cancel Voucher</button></div>
    </form>
</div></div></div>

@endsection
