<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>إيصال التسوية المبكرة — <?= e($receipt['receipt_number']) ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<button type="button" onclick="window.print()" class="btn btn-primary">
    <i data-lucide="printer" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> طباعة
</button>
<a href="/installments/<?= (int) $plan['id'] ?>" class="btn btn-outline">← خطة التقسيط</a>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<?php
$paymentMethodLabel = match ($receipt['payment_method'] ?? 'cash') {
    'cash'          => 'نقدي',
    'check'         => 'شيك',
    'visa'          => 'بطاقة فيزا',
    'bank_transfer' => 'تحويل بنكي',
    default         => e($receipt['payment_method'] ?? ''),
};
$totalPrincipalFloat = (float) $totalPrincipal;
$settlementAmount    = (float) $receipt['payment_amount'];
// Waived = original due - what was actually paid
// Sum the original amounts (principal = amount since we zeroed interest on save)
// Derive waived from plan data: original per-item amount stored in amount column before we changed it
// We stored paid_amount = principal, so waived = (originalDue that we can infer)
// Safer: re-derive from plan totals
$paidScheduleInterest = (float) \App\Core\App::getInstance()->db()->selectOne(
    "SELECT COALESCE(SUM(interest), 0) as s FROM installment_schedule WHERE installment_plan_id = ? AND status = 'paid'",
    [(int) $plan['id']]
)['s'];
// Items settled in this receipt: their interest is now 0, original interest was wiped.
// We'll just show settlement_amount vs total_with_interest remaining at the time.
// The description_ar on the receipt contains the full text, which is the source of truth.
?>

<!-- Print styles -->
<style>
@media print {
    .btn, nav, aside, header, .page-actions, .sidebar { display:none !important; }
    body { background:#fff !important; }
    .receipt-wrap { box-shadow:none !important; border:none !important; }
}
</style>

<div class="receipt-wrap" style="max-width:680px;margin:0 auto;background:#fff;border:1px solid #E5E7EB;border-radius:12px;overflow:hidden;box-shadow:0 2px 12px rgba(0,0,0,.06);">

    <!-- Header -->
    <div style="background:linear-gradient(135deg,#7C3AED,#5B21B6);padding:28px 32px;color:#fff;text-align:center;">
        <div style="font-size:11px;letter-spacing:2px;opacity:.8;margin-bottom:6px;">النادي الرياضي</div>
        <div style="font-size:22px;font-weight:800;margin-bottom:4px;">إيصال تسوية مبكرة</div>
        <div style="font-size:13px;opacity:.85;">Early Settlement Receipt</div>
        <div style="margin-top:14px;background:rgba(255,255,255,.15);display:inline-block;padding:6px 20px;border-radius:99px;font-size:15px;font-weight:700;letter-spacing:1px;">
            <?= e($receipt['receipt_number']) ?>
        </div>
    </div>

    <!-- Settlement badge -->
    <div style="background:#F0FDF4;border-bottom:1px solid #86EFAC;padding:12px 32px;display:flex;align-items:center;gap:10px;justify-content:center;">
        <i data-lucide="check-circle" style="width:20px;height:20px;color:#059669;"></i>
        <span style="font-size:13px;font-weight:700;color:#15803D;">تسوية مبكرة لجميع الأقساط المتبقية — تمت بنجاح</span>
    </div>

    <div style="padding:28px 32px;">

        <!-- Member & receipt meta -->
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:0;border:1px solid #E5E7EB;border-radius:8px;overflow:hidden;margin-bottom:24px;font-size:13px;">
            <div style="padding:11px 16px;border-left:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;">
                <div style="color:#9CA3AF;font-size:11px;margin-bottom:2px;">العضو</div>
                <div style="font-weight:700;"><?= e($plan['member_name']) ?></div>
            </div>
            <div style="padding:11px 16px;border-bottom:1px solid #E5E7EB;">
                <div style="color:#9CA3AF;font-size:11px;margin-bottom:2px;">رقم الاستمارة</div>
                <div style="font-weight:700;"><?= e($plan['form_number'] ?? '—') ?></div>
            </div>
            <div style="padding:11px 16px;border-left:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;">
                <div style="color:#9CA3AF;font-size:11px;margin-bottom:2px;">رقم العضوية</div>
                <div style="font-weight:700;"><?= e($plan['membership_number'] ?? '—') ?></div>
            </div>
            <div style="padding:11px 16px;border-bottom:1px solid #E5E7EB;">
                <div style="color:#9CA3AF;font-size:11px;margin-bottom:2px;">تاريخ الإيصال</div>
                <div style="font-weight:700;"><?= e(substr($receipt['issued_at'] ?? '', 0, 10)) ?></div>
            </div>
            <div style="padding:11px 16px;border-left:1px solid #E5E7EB;">
                <div style="color:#9CA3AF;font-size:11px;margin-bottom:2px;">طريقة الدفع</div>
                <div style="font-weight:700;"><?= $paymentMethodLabel ?></div>
            </div>
            <div style="padding:11px 16px;">
                <div style="color:#9CA3AF;font-size:11px;margin-bottom:2px;">المحصِّل</div>
                <div style="font-weight:700;"><?= e($receipt['cashier_name'] ?? '—') ?></div>
            </div>
        </div>

        <!-- Financial breakdown -->
        <div style="border:1px solid #E5E7EB;border-radius:8px;overflow:hidden;margin-bottom:24px;">
            <div style="padding:10px 16px;background:#F9FAFB;border-bottom:1px solid #E5E7EB;font-size:12px;font-weight:700;color:#374151;">
                تفاصيل التسوية
            </div>
            <table style="width:100%;border-collapse:collapse;font-size:13px;">
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:10px 16px;color:#6B7280;">عدد الأقساط المسوَّاة</td>
                    <td style="padding:10px 16px;font-weight:700;text-align:left;"><?= $itemsCount ?> قسط</td>
                </tr>
                <?php
                // Derive original total due = principal + original interest
                // Since we zero'd interest on save, we need another source.
                // The receipt description has it; or we can compute from plan:
                // original pending total = totalPrincipal + waivedInterest
                // We don't have waived stored separately, but receipt amount = principal paid
                // So waived = whatever the original amounts were minus principal.
                // Best approach: query the original totals from plan header.
                $planTotalWI    = (float) $plan['total_with_interest'];
                $planTotalInt   = (float) $plan['total_interest'];
                // Already-paid interest before this settlement
                $alreadyPaidInt = $paidScheduleInterest - 0; // settled items had interest zeroed so paid int = only previously paid
                // Actually paidScheduleInterest now includes settled items (all interest=0).
                // We need the original interest of the settled items.
                // Simplest: original_total_due = settlement_amount + waived_interest
                // waived_interest = total_interest_of_plan - interest_paid_before_this_settlement
                // But we don't have that cleanly. Use plan totals instead:
                // remaining_principal at settlement time = settlement_amount (what we charged)
                // total original due for pending = remaining_balance on plan at settlement
                $planRemainingBalance = (float) $plan['remaining_balance'];
                // remaining_balance in plan was updated... Let's just use what we know:
                // The receipt description_ar contains the exact breakdown text — use that as the narrative
                // For the table show: settlement_amount as principal, derive waived from receipt amount vs original
                // Simple: we have settlement_amount and items; original per-item interest was stored in schedule
                // but now zeroed. Compute from plan: total_interest - sum(interest of paid-before-settlement rows)
                $originalPendingInterest = 0.0; // will compute below
                foreach ($settledItems as $si) {
                    // interest is now 0; original = we can't recover exactly unless we stored it
                    // We know: settlement_amount = sum(principal). We know total_interest from plan.
                    // Best we can do: original_pending_interest = total_interest - already_paid_before
                    // already_paid_before = sum of interest on rows paid BEFORE this settlement
                    $originalPendingInterest = 0.0; // will do single query below
                }
                $prevPaidInterest = (float) \App\Core\App::getInstance()->db()->selectOne(
                    "SELECT COALESCE(SUM(is2.interest), 0) as s
                     FROM installment_schedule is2
                     WHERE is2.installment_plan_id = ?
                       AND is2.status = 'paid'
                       AND is2.payment_id != ?",
                    [(int) $plan['id'], (int) $receipt['payment_id']]
                )['s'];
                $originalPendingInterest = round($planTotalInt - $prevPaidInterest, 2);
                $originalPendingTotal    = round($totalPrincipalFloat + $originalPendingInterest, 2);
                ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:10px 16px;color:#6B7280;">الرصيد الأصلي المستحق</td>
                    <td style="padding:10px 16px;font-weight:700;text-align:left;color:#DC2626;"><?= money($originalPendingTotal) ?></td>
                </tr>
                <tr style="border-bottom:1px solid #F3F4F6;background:#FFF7ED;">
                    <td style="padding:10px 16px;color:#D97706;font-weight:600;">✂️ الفوائد الساقطة (خصم التسوية المبكرة)</td>
                    <td style="padding:10px 16px;font-weight:700;text-align:left;color:#059669;">− <?= money($originalPendingInterest) ?></td>
                </tr>
                <tr style="background:#F5F3FF;">
                    <td style="padding:12px 16px;font-weight:800;color:#7C3AED;font-size:14px;">المبلغ المحصَّل (أصل الدين فقط)</td>
                    <td style="padding:12px 16px;font-weight:900;text-align:left;color:#7C3AED;font-size:18px;"><?= money($settlementAmount) ?></td>
                </tr>
            </table>
        </div>

        <!-- Settled items list -->
        <div style="border:1px solid #E5E7EB;border-radius:8px;overflow:hidden;margin-bottom:24px;">
            <div style="padding:10px 16px;background:#F9FAFB;border-bottom:1px solid #E5E7EB;font-size:12px;font-weight:700;color:#374151;">
                الأقساط المسوَّاة (<?= $itemsCount ?>)
            </div>
            <table style="width:100%;border-collapse:collapse;font-size:12px;">
                <thead>
                    <tr style="background:#F9FAFB;border-bottom:1px solid #E5E7EB;">
                        <th style="padding:7px 12px;text-align:right;color:#6B7280;">#</th>
                        <th style="padding:7px 12px;text-align:right;color:#6B7280;">تاريخ الاستحقاق</th>
                        <th style="padding:7px 12px;text-align:right;color:#6B7280;">المبلغ المسدد</th>
                        <th style="padding:7px 12px;text-align:right;color:#6B7280;">الحالة</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($settledItems as $si): ?>
                    <tr style="border-bottom:1px solid #F3F4F6;">
                        <td style="padding:6px 12px;font-weight:600;"><?= (int) $si['installment_number'] ?></td>
                        <td style="padding:6px 12px;"><?= e($si['due_date']) ?></td>
                        <td style="padding:6px 12px;font-weight:600;"><?= money($si['paid_amount']) ?></td>
                        <td style="padding:6px 12px;color:#059669;font-weight:700;">✅ مسدد</td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Amount in words -->
        <div style="background:#F5F3FF;border:1px solid #DDD6FE;border-radius:8px;padding:14px 18px;margin-bottom:24px;text-align:center;">
            <div style="font-size:11px;color:#7C3AED;margin-bottom:4px;">المبلغ كتابةً</div>
            <div style="font-size:14px;font-weight:700;color:#4C1D95;"><?= e($receipt['amount_in_words_ar'] ?? '—') ?></div>
        </div>

        <!-- Stamp area -->
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:8px;">
            <div style="border:1px dashed #D1D5DB;border-radius:8px;padding:20px;text-align:center;">
                <div style="font-size:11px;color:#9CA3AF;margin-bottom:30px;">توقيع المحصِّل</div>
                <div style="border-top:1px solid #D1D5DB;padding-top:6px;font-size:11px;color:#6B7280;"><?= e($receipt['cashier_name'] ?? '—') ?></div>
            </div>
            <div style="border:1px dashed #D1D5DB;border-radius:8px;padding:20px;text-align:center;">
                <div style="font-size:11px;color:#9CA3AF;margin-bottom:30px;">ختم النادي</div>
                <div style="border-top:1px solid #D1D5DB;padding-top:6px;font-size:11px;color:#6B7280;">&nbsp;</div>
            </div>
        </div>

    </div>

    <!-- Footer -->
    <div style="background:#F9FAFB;border-top:1px solid #E5E7EB;padding:12px 32px;text-align:center;font-size:11px;color:#9CA3AF;">
        هذا الإيصال يُثبت التسوية المبكرة لخطة التقسيط #<?= (int) $plan['id'] ?> — <?= e($receipt['issued_at'] ?? '') ?>
    </div>

</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    if (typeof lucide !== 'undefined') lucide.createIcons();
});
</script>

<?php $__template->endSection(); ?>
