@extends('layouts.app')

@section('title', 'Savings Receipt')
@section('page-title', 'Savings Receipt')

@section('content')
@php
    $tenant = auth()->user()->tenant;
    $account = $transaction->account;
    $member = $transaction->customer ?: $account?->customer;
    $currency = $tenant->settings['currency'] ?? 'NGN';
    $money = fn ($amount) => $currency.' '.number_format((float) $amount, 2);
    $status = $transaction->status ?? 'posted';
    $isWithdrawal = $transaction->type === 'withdrawal';
    $receiptType = $isWithdrawal ? 'Savings Withdrawal Receipt' : 'Savings Deposit Receipt';
    $receiptDate = app_datetime($transaction->transacted_at ?: $transaction->created_at ?: now());
    $processingFee = (float) ($transaction->processing_fee_amount ?? 0);
    $grossAmount = (float) $transaction->amount;
    $netAmount = (float) ($transaction->net_amount ?? 0);

    if ($netAmount <= 0 && $processingFee < $grossAmount) {
        $netAmount = $isWithdrawal ? $grossAmount - $processingFee : $grossAmount - $processingFee;
    }

    $netLabel = $isWithdrawal ? 'Net payout' : 'Net saved';
    $amountLabel = $isWithdrawal ? 'Amount deducted' : 'Amount received';
    $statusClass = match ($status) {
        'posted' => 'success',
        'pending' => 'warning',
        'rejected', 'canceled' => 'secondary',
        default => 'light',
    };
    $statusText = match ($status) {
        'posted' => $isWithdrawal ? 'Withdrawal posted' : 'Deposit posted',
        'pending' => 'Pending approval',
        'rejected' => 'Rejected',
        'canceled' => 'Canceled / reversed',
        default => str($status)->headline()->toString(),
    };
@endphp

<div class="receipt-actions no-print">
    @if($account)
        <a href="{{ route('tenant.savings.show', $account) }}" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-1"></i> Savings account
        </a>
    @endif
    <a href="{{ $isWithdrawal ? route('tenant.withdrawals.index') : route('tenant.savings.index') }}" class="btn btn-outline-primary">
        <i class="bi {{ $isWithdrawal ? 'bi-cash-coin' : 'bi-piggy-bank' }} me-1"></i> {{ $isWithdrawal ? 'Withdrawals' : 'Savings' }}
    </a>
    <button type="button" onclick="printStandardReceipt()" class="btn btn-primary">
        <i class="bi bi-printer me-1"></i> Print full receipt
    </button>
    <button type="button" onclick="printThermalReceipt()" class="btn btn-dark">
        <i class="bi bi-receipt-cutoff me-1"></i> Print thermal
    </button>
</div>

<section class="savings-receipt mx-auto">
    <div class="receipt-topbar {{ $isWithdrawal ? 'withdrawal' : 'deposit' }}"></div>

    <header class="receipt-header">
        <div class="receipt-brand">
            @if($tenant?->displayLogoUrl())
                <img src="{{ $tenant->displayLogoUrl() }}" alt="{{ $tenant->name }}">
            @else
                <div class="receipt-logo-fallback">{{ str($tenant?->name ?? 'MFI')->substr(0, 2)->upper() }}</div>
            @endif
            <div>
                <h2>{{ $tenant?->name }}</h2>
                <p>{{ $tenant?->address ?: 'Savings and withdrawal receipt' }}</p>
                @if($tenant?->phone)
                    <small>{{ $tenant->phone }}</small>
                @endif
            </div>
        </div>

        <div class="receipt-ref">
            <span>Receipt No.</span>
            <strong>{{ $transaction->reference }}</strong>
            <small>{{ $receiptDate }}</small>
        </div>
    </header>

    <div class="receipt-status-row {{ $statusClass }}">
        <span><i class="bi {{ $status === 'posted' ? 'bi-check-circle-fill' : ($status === 'pending' ? 'bi-clock-fill' : 'bi-info-circle-fill') }}"></i> {{ $statusText }}</span>
        <span>{{ ucfirst($transaction->method ?? 'cash') }}</span>
    </div>

    @if($status === 'canceled')
        <div class="receipt-cancel-alert">
            <strong>This receipt has been canceled.</strong>
            <span>Reversed by {{ $transaction->canceler?->name ?? 'admin' }} {{ $transaction->canceled_at ? 'on '.app_datetime($transaction->canceled_at) : '' }}.</span>
            @if(filled($transaction->canceled_reason))
                <small>{{ $transaction->canceled_reason }}</small>
            @endif
        </div>
    @endif

    <section class="receipt-amount-panel">
        <div>
            <span>{{ $amountLabel }}</span>
            <strong>{{ $money($grossAmount) }}</strong>
        </div>
        <div>
            <span>{{ $netLabel }}</span>
            <strong>{{ $money($processingFee > 0 ? $netAmount : $grossAmount) }}</strong>
        </div>
        <div>
            <span>Balance after transaction</span>
            <strong>{{ $money($transaction->balance_after) }}</strong>
        </div>
    </section>

    <div class="receipt-grid">
        <section class="receipt-section">
            <h3>Member Details</h3>
            <div class="receipt-line"><span>Name</span><strong>{{ $member?->fullName() }}</strong></div>
            <div class="receipt-line"><span>Member account</span><strong>{{ $member?->account_number ?? '-' }}</strong></div>
            <div class="receipt-line"><span>Phone</span><strong>{{ $member?->phone ?? '-' }}</strong></div>
        </section>

        <section class="receipt-section">
            <h3>Savings Details</h3>
            <div class="receipt-line"><span>Savings account</span><strong>{{ $account?->account_number ?? '-' }}</strong></div>
            <div class="receipt-line"><span>Product</span><strong>{{ $account?->product_name ?: $account?->typeLabel() }}</strong></div>
            <div class="receipt-line"><span>Status</span><strong>{{ ucfirst($account?->status ?? '-') }}</strong></div>
        </section>
    </div>

    <section class="receipt-section receipt-components">
        <div class="receipt-section-head">
            <h3>Transaction Breakdown</h3>
            <span>{{ $receiptType }}</span>
        </div>
        <div class="component-table">
            <div><span>{{ $amountLabel }}</span><strong>{{ $money($grossAmount) }}</strong></div>
            @if($processingFee > 0)
                <div><span>Processing fee</span><strong>{{ $money($processingFee) }}</strong></div>
                <div><span>{{ $netLabel }}</span><strong>{{ $money($netAmount) }}</strong></div>
            @endif
            <div><span>Balance before</span><strong>{{ $money($transaction->balance_before) }}</strong></div>
            <div><span>Balance after</span><strong>{{ $money($transaction->balance_after) }}</strong></div>
        </div>
    </section>

    <section class="receipt-section">
        <h3>Posting Details</h3>
        <div class="receipt-line"><span>Initiated by</span><strong>{{ $transaction->creator?->name ?? 'System / member' }}</strong></div>
        <div class="receipt-line">
            <span>{{ $status === 'canceled' ? 'Canceled by' : 'Approved by' }}</span>
            <strong>
                @if($status === 'canceled')
                    {{ $transaction->canceler?->name ?? 'Admin' }}
                @else
                    {{ $transaction->approver?->name ?? ($status === 'pending' ? 'Not approved yet' : 'Auto-posted') }}
                @endif
            </strong>
        </div>
        @if(filled($transaction->description))
            <div class="receipt-note">{{ $transaction->description }}</div>
        @endif
    </section>

    <footer class="receipt-footer">
        <div>
            <strong>{{ $status === 'canceled' ? 'Transaction reversed.' : 'Thank you.' }}</strong>
            <span>
                @if($status === 'canceled')
                    This document is retained for audit trail only.
                @else
                    This receipt confirms the {{ strtolower($receiptType) }} above.
                @endif
            </span>
        </div>
        <div class="receipt-signature">
            <span></span>
            Authorized signature
        </div>
    </footer>
</section>

<section class="thermal-savings-receipt">
    <div class="thermal-center">
        <strong>{{ $tenant?->name }}</strong>
        @if($tenant?->address)
            <span>{{ $tenant->address }}</span>
        @endif
        @if($tenant?->phone)
            <span>{{ $tenant->phone }}</span>
        @endif
    </div>

    <div class="thermal-rule"></div>
    <div class="thermal-title">{{ strtoupper($receiptType) }}</div>
    <div class="thermal-rule"></div>

    <div class="thermal-row"><span>Receipt:</span><strong>{{ $transaction->reference }}</strong></div>
    <div class="thermal-row"><span>Date:</span><strong>{{ $receiptDate }}</strong></div>
    <div class="thermal-row"><span>Status:</span><strong>{{ ucfirst($status) }}</strong></div>
    <div class="thermal-row"><span>Method:</span><strong>{{ ucfirst($transaction->method ?? 'cash') }}</strong></div>

    <div class="thermal-rule"></div>
    <div class="thermal-row"><span>Member:</span><strong>{{ $member?->fullName() }}</strong></div>
    <div class="thermal-row"><span>Acct:</span><strong>{{ $member?->account_number ?? '-' }}</strong></div>
    <div class="thermal-row"><span>Savings:</span><strong>{{ $account?->account_number ?? '-' }}</strong></div>
    <div class="thermal-row"><span>Product:</span><strong>{{ $account?->product_name ?: '-' }}</strong></div>

    <div class="thermal-rule"></div>
    <div class="thermal-row thermal-amount"><span>{{ $isWithdrawal ? 'Deducted:' : 'Received:' }}</span><strong>{{ $money($grossAmount) }}</strong></div>
    @if($processingFee > 0)
        <div class="thermal-row"><span>Fee:</span><strong>{{ $money($processingFee) }}</strong></div>
        <div class="thermal-row thermal-amount"><span>{{ $isWithdrawal ? 'Net payout:' : 'Net saved:' }}</span><strong>{{ $money($netAmount) }}</strong></div>
    @endif
    <div class="thermal-row"><span>Before:</span><strong>{{ $money($transaction->balance_before) }}</strong></div>
    <div class="thermal-row thermal-amount"><span>Balance:</span><strong>{{ $money($transaction->balance_after) }}</strong></div>

    <div class="thermal-rule"></div>
    <div class="thermal-row"><span>Initiated:</span><strong>{{ $transaction->creator?->name ?? 'System' }}</strong></div>
    <div class="thermal-row">
        <span>{{ $status === 'canceled' ? 'Canceled:' : 'Approved:' }}</span>
        <strong>{{ $status === 'canceled' ? ($transaction->canceler?->name ?? 'Admin') : ($transaction->approver?->name ?? ($status === 'pending' ? 'Pending' : 'Auto')) }}</strong>
    </div>
    @if($status === 'canceled')
        <div class="thermal-rule"></div>
        <div class="thermal-center thermal-footer-text">
            <span>TRANSACTION CANCELED</span>
            @if(filled($transaction->canceled_reason))
                <span>{{ $transaction->canceled_reason }}</span>
            @endif
        </div>
    @endif

    <div class="thermal-center thermal-footer-text">
        <span>{{ $status === 'canceled' ? 'Audit copy only.' : 'Transaction posted successfully.' }}</span>
        <span>Thank you.</span>
    </div>
</section>

<style>
.receipt-actions {
    display: flex;
    justify-content: center;
    gap: .65rem;
    margin-bottom: 1rem;
    flex-wrap: wrap;
}
.thermal-savings-receipt {
    display: none;
}
.savings-receipt {
    max-width: 900px;
    overflow: hidden;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    background: #fff;
    box-shadow: 0 1rem 2.5rem rgba(15, 23, 42, .08);
}
.receipt-topbar {
    height: 10px;
    background: linear-gradient(90deg, #0f766e, #1d4ed8, #f59e0b);
}
.receipt-topbar.withdrawal {
    background: linear-gradient(90deg, #7c2d12, #dc2626, #f59e0b);
}
.receipt-header {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    padding: 1.35rem;
    border-bottom: 1px solid #e2e8f0;
}
.receipt-brand {
    display: flex;
    gap: .9rem;
    min-width: 0;
}
.receipt-brand img,
.receipt-logo-fallback {
    width: 58px;
    height: 58px;
    border-radius: 10px;
    object-fit: cover;
    flex: 0 0 auto;
}
.receipt-logo-fallback {
    display: grid;
    place-items: center;
    color: #fff;
    background: #0f766e;
    font-weight: 800;
}
.receipt-brand h2 {
    margin: 0;
    color: #0f172a;
    font-size: 1.35rem;
}
.receipt-brand p,
.receipt-brand small {
    display: block;
    margin: .2rem 0 0;
    color: #64748b;
}
.receipt-ref {
    min-width: 210px;
    padding: .8rem;
    border-radius: 10px;
    text-align: right;
    background: #f8fafc;
}
.receipt-ref span,
.receipt-ref small {
    display: block;
    color: #64748b;
    font-size: .8rem;
}
.receipt-ref strong {
    display: block;
    margin: .15rem 0;
    color: #0f172a;
    font-size: 1rem;
}
.receipt-status-row {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    padding: .8rem 1.35rem;
    font-weight: 800;
}
.receipt-status-row span {
    display: inline-flex;
    align-items: center;
    gap: .4rem;
}
.receipt-status-row.success {
    color: #166534;
    background: #f0fdf4;
}
.receipt-status-row.warning {
    color: #92400e;
    background: #fffbeb;
}
.receipt-status-row.secondary {
    color: #334155;
    background: #f1f5f9;
}
.receipt-status-row.light {
    color: #475569;
    background: #f8fafc;
}
.receipt-cancel-alert {
    display: grid;
    gap: .25rem;
    margin: 1rem 1.35rem 0;
    padding: .85rem 1rem;
    border: 1px solid #cbd5e1;
    border-radius: 10px;
    color: #334155;
    background: #f8fafc;
}
.receipt-cancel-alert small,
.receipt-cancel-alert span {
    color: #64748b;
}
.receipt-amount-panel {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: .8rem;
    padding: 1.35rem;
}
.receipt-amount-panel > div {
    padding: 1rem;
    border-radius: 10px;
    color: #fff;
    background: linear-gradient(135deg, #0f172a, #0f766e);
}
.receipt-amount-panel > div:nth-child(2) {
    background: linear-gradient(135deg, #1e3a8a, #1d4ed8);
}
.receipt-amount-panel > div:nth-child(3) {
    background: linear-gradient(135deg, #92400e, #f59e0b);
}
.receipt-amount-panel span {
    display: block;
    color: rgba(255, 255, 255, .76);
    font-size: .82rem;
}
.receipt-amount-panel strong {
    display: block;
    margin-top: .25rem;
    font-size: 1.35rem;
}
.receipt-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 1rem;
    padding: 0 1.35rem 1.35rem;
}
.receipt-section {
    padding: 1rem;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    background: #fff;
}
.receipt-section + .receipt-section {
    margin: 0 1.35rem 1.35rem;
}
.receipt-grid .receipt-section + .receipt-section {
    margin: 0;
}
.receipt-section h3,
.receipt-section-head h3 {
    margin: 0 0 .75rem;
    color: #334155;
    font-size: .84rem;
    font-weight: 800;
    text-transform: uppercase;
}
.receipt-section-head {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    align-items: center;
}
.receipt-section-head span {
    color: #64748b;
    font-size: .82rem;
}
.receipt-line {
    display: flex;
    justify-content: space-between;
    gap: .8rem;
    padding: .5rem 0;
    border-bottom: 1px dashed #e2e8f0;
}
.receipt-line:last-child {
    border-bottom: 0;
}
.receipt-line span {
    color: #64748b;
}
.receipt-line strong {
    color: #0f172a;
    text-align: right;
    overflow-wrap: anywhere;
}
.receipt-components {
    margin: 0 1.35rem 1.35rem;
}
.component-table {
    display: grid;
    gap: .55rem;
}
.component-table div {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    padding: .75rem;
    border-radius: 8px;
    background: #f8fafc;
}
.component-table span {
    color: #64748b;
}
.component-table strong {
    color: #0f172a;
}
.receipt-note {
    margin-top: .75rem;
    padding: .75rem;
    border-radius: 8px;
    color: #475569;
    white-space: pre-line;
    background: #f8fafc;
}
.receipt-footer {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    padding: 1.2rem 1.35rem;
    border-top: 1px solid #e2e8f0;
    background: #f8fafc;
}
.receipt-footer strong,
.receipt-footer span {
    display: block;
}
.receipt-footer span {
    color: #64748b;
    font-size: .86rem;
}
.receipt-signature {
    min-width: 180px;
    color: #64748b;
    text-align: center;
    font-size: .82rem;
}
.receipt-signature span {
    display: block;
    height: 34px;
    border-bottom: 1px solid #94a3b8;
    margin-bottom: .35rem;
}
@media (max-width: 767.98px) {
    .receipt-header,
    .receipt-footer,
    .receipt-status-row {
        display: grid;
    }
    .receipt-ref {
        text-align: left;
    }
    .receipt-amount-panel,
    .receipt-grid {
        grid-template-columns: 1fr;
    }
}
@media print {
    .no-print,
    .sidebar,
    .navbar,
    nav {
        display: none !important;
    }
    body {
        background: #fff !important;
    }
    .savings-receipt {
        max-width: 100%;
        border-radius: 0;
        box-shadow: none;
    }
    body.thermal-printing .savings-receipt {
        display: none !important;
    }
    body.thermal-printing .thermal-savings-receipt {
        display: block !important;
        width: 76mm;
        max-width: 76mm;
        margin: 0 auto;
        padding: 0;
        color: #000;
        background: #fff;
        font-family: "Courier New", monospace;
        font-size: 11px;
        line-height: 1.25;
        box-shadow: none;
    }
    body.thermal-printing .main-content,
    body.thermal-printing .content,
    body.thermal-printing .container,
    body.thermal-printing .container-fluid {
        margin: 0 !important;
        padding: 0 !important;
        max-width: none !important;
    }
}
.thermal-center {
    display: grid;
    gap: 2px;
    text-align: center;
}
.thermal-center strong {
    font-size: 13px;
    text-transform: uppercase;
}
.thermal-center span {
    display: block;
}
.thermal-title {
    text-align: center;
    font-weight: 800;
}
.thermal-rule {
    border-top: 1px dashed #000;
    margin: 6px 0;
}
.thermal-row {
    display: flex;
    justify-content: space-between;
    gap: 8px;
    padding: 2px 0;
}
.thermal-row span {
    flex: 0 0 auto;
}
.thermal-row strong {
    text-align: right;
    overflow-wrap: anywhere;
}
.thermal-amount {
    font-size: 12px;
    font-weight: 800;
}
.thermal-footer-text {
    margin-top: 8px;
}
</style>

<script>
function printStandardReceipt() {
    document.body.classList.remove('thermal-printing');
    window.print();
}

function printThermalReceipt() {
    document.body.classList.add('thermal-printing');
    window.print();
    setTimeout(() => document.body.classList.remove('thermal-printing'), 1500);
}

window.addEventListener('afterprint', () => {
    document.body.classList.remove('thermal-printing');
});
</script>
@endsection
