@extends('layouts.app')

@section('title', 'Message Units')
@section('page-title', 'Message Units')
@section('page-subtitle', 'Approve tenant SMS/WhatsApp unit purchases and review usage')

@section('content')
@php
    $money = fn ($amount) => 'NGN '.number_format((float) $amount, 2);
    $pendingTopups = $topups->getCollection()->where('status', 'pending')->count();
    $memberCharges = (float) $wallets->sum(fn ($wallet) => (float) $wallet->total_member_charges);
    $usedCost = (float) $wallets->sum(fn ($wallet) => (float) $wallet->total_used_cost);
@endphp

<section class="section-hero mb-4">
    <div class="section-hero-copy">
        <span>Platform wallet control</span>
        <h2>Manage tenant SMS and WhatsApp units</h2>
        <p>Tenants buy units before sending paid SMS or WhatsApp notifications. Approve manual payments, credit bonuses, and audit every usage record.</p>
    </div>
    <div class="section-hero-panel">
        <span>Pending approvals</span>
        <strong>{{ number_format($pendingTopups) }}</strong>
        <small>{{ number_format($wallets->sum('balance_units')) }} total tenant units available</small>
    </div>
</section>

<div class="section-stat-grid mb-4">
    <div class="section-stat-card">
        <i class="bi bi-phone"></i>
        <span>SMS price</span>
        <strong>{{ $money($platformPrices['sms'] ?? 0) }}</strong>
        <small>Tenant purchase price per unit</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-whatsapp"></i>
        <span>WhatsApp price</span>
        <strong>{{ $money($platformPrices['whatsapp'] ?? 0) }}</strong>
        <small>Tenant purchase price per unit</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-hourglass-split"></i>
        <span>Pending</span>
        <strong>{{ number_format($pendingTopups) }}</strong>
        <small>Manual payments to review</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-send-check"></i>
        <span>Tenant profit</span>
        <strong>{{ $money($memberCharges - $usedCost) }}</strong>
        <small>{{ $money($memberCharges) }} charged less {{ $money($usedCost) }} unit cost</small>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-4">
        <div class="section-form-card">
            <div class="section-card-title">
                <span><i class="bi bi-plus-circle"></i></span>
                <div>
                    <strong>Credit tenant units</strong>
                    <small>Use for bonuses, corrections, or manual allocations.</small>
                </div>
            </div>
            <form method="POST" action="{{ route('super.communication-units.credit') }}" class="row g-3">
                @csrf
                <div class="col-12">
                    <label class="form-label">Tenant</label>
                    <select name="tenant_id" class="form-select" required>
                        @foreach($tenants as $tenant)
                            <option value="{{ $tenant->id }}">{{ $tenant->name }} - {{ $tenant->email }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label">Channel</label>
                    <select name="channel" class="form-select" required>
                        @foreach($channels as $channel => $label)
                            <option value="{{ $channel }}">{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label">Units</label>
                    <input name="units" type="number" min="1" value="100" class="form-control" required>
                </div>
                <div class="col-12">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" class="form-control" rows="3" placeholder="Bonus, correction, promo, or manual allocation"></textarea>
                </div>
                <div class="col-12 d-grid">
                    <button class="btn btn-primary"><i class="bi bi-check2-circle me-1"></i> Credit units now</button>
                </div>
            </form>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="section-workspace">
            <div class="section-tabbar">
                <ul class="nav section-tabs" role="tablist">
                    <li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#topups-pane" type="button">Top-ups</button></li>
                    <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#wallets-pane" type="button">Wallets</button></li>
                    <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#ledger-pane" type="button">Ledger</button></li>
                </ul>
            </div>
            <div class="tab-content">
                <div class="tab-pane fade show active" id="topups-pane" role="tabpanel" tabindex="0">
                    <div class="section-pane-head">
                        <div><span>Approvals</span><h3>Tenant unit payments</h3></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table section-table align-middle mb-0">
                            <thead><tr><th>Tenant</th><th>Reference</th><th>Channel</th><th>Units</th><th>Amount</th><th>Status</th><th>Action</th></tr></thead>
                            <tbody>
                            @forelse($topups as $topup)
                                <tr>
                                    <td>{{ $topup->tenant?->name }}</td>
                                    <td>
                                        <div class="fw-semibold">{{ $topup->reference }}</div>
                                        <small class="text-muted">{{ ucfirst($topup->payment_channel) }} · {{ app_datetime($topup->created_at) }}</small>
                                    </td>
                                    <td>{{ $topup->channelLabel() }}</td>
                                    <td>{{ number_format($topup->units) }}</td>
                                    <td>{{ $money($topup->amount) }}</td>
                                    <td><span class="badge text-bg-{{ $topup->status === 'approved' ? 'success' : ($topup->status === 'rejected' ? 'danger' : 'warning') }}">{{ ucfirst($topup->status) }}</span></td>
                                    <td>
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                Action
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                                                <li>
                                                    <button type="button" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#topupView{{ $topup->id }}">
                                                        <i class="bi bi-eye me-2"></i> View proof
                                                    </button>
                                                </li>
                                                @if($topup->status === 'pending')
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li>
                                                        <form method="POST" action="{{ route('super.communication-units.approve', $topup) }}">
                                                            @csrf
                                                            <button class="dropdown-item text-success">
                                                                <i class="bi bi-check2-circle me-2"></i> Approve
                                                            </button>
                                                        </form>
                                                    </li>
                                                    <li>
                                                        <button type="button" class="dropdown-item text-danger" data-bs-toggle="modal" data-bs-target="#topupReject{{ $topup->id }}">
                                                            <i class="bi bi-x-circle me-2"></i> Reject
                                                        </button>
                                                    </li>
                                                @endif
                                            </ul>
                                        </div>
                                    </td>
                                </tr>
                            @empty
                                <tr><td colspan="7" class="text-center text-muted py-4">No unit payments yet.</td></tr>
                            @endforelse
                            </tbody>
                        </table>
                    </div>

                    @foreach($topups as $topup)
                        @php
                            $proofUrl = $topup->proof_path ? asset('uploads/'.$topup->proof_path) : null;
                            $proofExtension = strtolower(pathinfo((string) $topup->proof_path, PATHINFO_EXTENSION));
                            $proofIsImage = in_array($proofExtension, ['jpg', 'jpeg', 'png', 'webp'], true);
                        @endphp
                        <div class="modal fade" id="topupView{{ $topup->id }}" tabindex="-1" aria-labelledby="topupView{{ $topup->id }}Label" aria-hidden="true">
                            <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <div>
                                            <h5 class="modal-title" id="topupView{{ $topup->id }}Label">Unit payment proof</h5>
                                            <div class="text-muted small">{{ $topup->reference }} - {{ $topup->tenant?->name }}</div>
                                        </div>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        <div class="row g-3 mb-3">
                                            <div class="col-md-4">
                                                <div class="border rounded-3 p-3 h-100">
                                                    <span class="text-muted small">Channel</span>
                                                    <div class="fw-semibold">{{ $topup->channelLabel() }}</div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="border rounded-3 p-3 h-100">
                                                    <span class="text-muted small">Units</span>
                                                    <div class="fw-semibold">{{ number_format($topup->units) }}</div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="border rounded-3 p-3 h-100">
                                                    <span class="text-muted small">Amount</span>
                                                    <div class="fw-semibold">{{ $money($topup->amount) }}</div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="border rounded-3 p-3 h-100">
                                                    <span class="text-muted small">Initiated by</span>
                                                    <div class="fw-semibold">{{ $topup->creator?->name ?? 'System' }}</div>
                                                    <small class="text-muted">{{ app_datetime($topup->created_at) }}</small>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="border rounded-3 p-3 h-100">
                                                    <span class="text-muted small">Processed by</span>
                                                    <div class="fw-semibold">{{ $topup->approver?->name ?? '-' }}</div>
                                                    <small class="text-muted">{{ $topup->processed_at ? app_datetime($topup->processed_at) : 'Not processed yet' }}</small>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <div class="fw-semibold mb-2">Payment proof</div>
                                            @if($proofUrl && $proofIsImage)
                                                <a href="{{ $proofUrl }}" target="_blank" rel="noopener">
                                                    <img src="{{ $proofUrl }}" alt="Payment proof for {{ $topup->reference }}" class="img-fluid rounded-3 border">
                                                </a>
                                            @elseif($proofUrl)
                                                <div class="border rounded-3 p-3 bg-light d-flex flex-wrap gap-2 justify-content-between align-items-center">
                                                    <div>
                                                        <div class="fw-semibold">Receipt attached</div>
                                                        <small class="text-muted">{{ strtoupper($proofExtension ?: 'FILE') }} payment proof</small>
                                                    </div>
                                                    <a href="{{ $proofUrl }}" target="_blank" rel="noopener" class="btn btn-sm btn-outline-primary">
                                                        <i class="bi bi-box-arrow-up-right me-1"></i> Open receipt
                                                    </a>
                                                </div>
                                            @else
                                                <div class="alert alert-warning mb-0">No payment proof was attached to this top-up.</div>
                                            @endif
                                        </div>

                                        @if(filled($topup->notes))
                                            <div class="mb-3">
                                                <div class="fw-semibold mb-2">Tenant notes</div>
                                                <div class="border rounded-3 p-3 bg-light">{{ $topup->notes }}</div>
                                            </div>
                                        @endif

                                        @if(filled($topup->rejected_reason))
                                            <div>
                                                <div class="fw-semibold mb-2">Rejection reason</div>
                                                <div class="border rounded-3 p-3 bg-danger-subtle text-danger-emphasis">{{ $topup->rejected_reason }}</div>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                                        @if($topup->status === 'pending')
                                            <form method="POST" action="{{ route('super.communication-units.approve', $topup) }}">
                                                @csrf
                                                <button class="btn btn-success"><i class="bi bi-check2-circle me-1"></i> Approve</button>
                                            </form>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>

                        @if($topup->status === 'pending')
                            <div class="modal fade" id="topupReject{{ $topup->id }}" tabindex="-1" aria-labelledby="topupReject{{ $topup->id }}Label" aria-hidden="true">
                                <div class="modal-dialog modal-dialog-centered">
                                    <div class="modal-content">
                                        <form method="POST" action="{{ route('super.communication-units.reject', $topup) }}">
                                            @csrf
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="topupReject{{ $topup->id }}Label">Reject unit payment</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <div class="modal-body">
                                                <div class="alert alert-warning small">Rejecting {{ $topup->reference }} will not credit {{ $topup->tenant?->name }} with units.</div>
                                                <label class="form-label">Reason</label>
                                                <textarea name="rejected_reason" class="form-control" rows="4" required placeholder="Why was this payment proof rejected?"></textarea>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                                                <button class="btn btn-danger"><i class="bi bi-x-circle me-1"></i> Reject payment</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        @endif
                    @endforeach

                    <div class="p-3">{{ $topups->links() }}</div>
                </div>

                <div class="tab-pane fade" id="wallets-pane" role="tabpanel" tabindex="0">
                    <div class="section-pane-head">
                        <div><span>Balances</span><h3>Tenant communication wallets</h3></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table section-table mb-0">
                            <thead><tr><th>Tenant</th><th>Channel</th><th>Balance</th><th>Wallet value</th><th>Credited</th><th>Used</th><th>Cost used</th><th>Member charges</th></tr></thead>
                            <tbody>
                            @forelse($wallets as $wallet)
                                <tr>
                                    <td>{{ $wallet->tenant?->name }}</td>
                                    <td>{{ $wallet->channelLabel() }}</td>
                                    <td class="fw-semibold">{{ number_format($wallet->balance_units) }}</td>
                                    <td>{{ $money($wallet->cost_balance) }}</td>
                                    <td>{{ number_format($wallet->total_credited_units) }}</td>
                                    <td>{{ number_format($wallet->total_used_units) }}</td>
                                    <td>{{ $money($wallet->total_used_cost) }}</td>
                                    <td>{{ $money($wallet->total_member_charges) }}</td>
                                </tr>
                            @empty
                                <tr><td colspan="8" class="text-center text-muted py-4">No wallets yet.</td></tr>
                            @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="tab-pane fade" id="ledger-pane" role="tabpanel" tabindex="0">
                    <div class="section-pane-head">
                        <div><span>Audit</span><h3>Unit ledger</h3></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table section-table mb-0">
                            <thead><tr><th>Date</th><th>Tenant</th><th>Channel</th><th>Type</th><th>Units</th><th>Member</th><th>Charge</th><th>Cost</th></tr></thead>
                            <tbody>
                            @forelse($transactions as $transaction)
                                <tr>
                                    <td>{{ app_datetime($transaction->created_at) }}</td>
                                    <td>{{ $transaction->tenant?->name }}</td>
                                    <td>{{ $transaction->channelLabel() }}</td>
                                    <td>{{ ucfirst($transaction->type) }}</td>
                                    <td>{{ $transaction->direction === 'debit' ? '-' : '+' }}{{ number_format($transaction->units) }}</td>
                                    <td>{{ $transaction->customer?->fullName() ?? '-' }}</td>
                                    <td>{{ $money($transaction->amount) }}</td>
                                    <td>{{ $money($transaction->cost_amount) }}</td>
                                </tr>
                            @empty
                                <tr><td colspan="8" class="text-center text-muted py-4">No unit activity yet.</td></tr>
                            @endforelse
                            </tbody>
                        </table>
                    </div>
                    <div class="p-3">{{ $transactions->links() }}</div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
