<?php
/**
 * Couple Portal — Budget Category Details (PRI-002 / UX002)
 * Location: app/views/budget/detail.php
 */

if (!function_exists('format_money')) {
    function format_money(float $amount, string $currency = 'IDR'): string
    {
        if ($currency === 'IDR') {
            return 'Rp ' . number_format($amount, 0, ',', '.');
        }
        return $currency . ' ' . number_format($amount, 2, '.', ',');
    }
}

$id       = (int) $expense['id'];
$currency = $summary['currency'] ?? 'IDR';
$estCost  = (float) $expense['estimated_cost'];
$actCost  = (float) $expense['actual_cost'];
$target   = $actCost > 0 ? $actCost : $estCost;

$paymentProgress = 0.0;
if ($target > 0) {
    $paymentProgress = min(100.0, ($total_paid / $target) * 100);
}

// Vendor contact
$hasVendor = !empty($expense['vendor_name']);
$hasPic    = !empty($expense['vendor_pic']);
$hasPhone  = !empty($expense['vendor_phone']);

$waLink = null;
if ($hasPhone) {
    $cleanPhone = preg_replace('/[^0-9]/', '', $expense['vendor_phone']);
    if (strpos($cleanPhone, '0') === 0) {
        $cleanPhone = '62' . substr($cleanPhone, 1);
    }
    $waLink = 'https://wa.me/' . $cleanPhone;
}

// Next payment status
$hasDueDate   = !empty($expense['due_date']);
$dueDateLabel = $hasDueDate ? date('d M Y', strtotime($expense['due_date'])) : null;

// Payment fully completed?
$isFullyPaid = $target > 0 && $total_paid >= $target;
?>

<div class="max-w-6xl mx-auto space-y-6" x-data="{ showPaymentForm: false }">

    <!-- ── Header ──────────────────────────────────────────────────────── -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
            <div class="page-breadcrumb">
                <a href="<?= url('/app/couple/budget') ?>">Budget Planner</a>
                <span class="sep">/</span>
                <span><?= escape_html($expense['category_name']) ?></span>
            </div>
            <h1 class="text-2xl font-black tracking-tight text-slate-800">
                <?= escape_html($expense['name'] ?? $expense['category_name']) ?>
            </h1>
            <?php if (!empty($expense['status'])): ?>
                <span class="inline-flex items-center gap-1.5 mt-2 px-2.5 py-0.5 rounded-full text-[11px] font-semibold
                    <?= $expense['status'] === 'Completed' ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' :
                        ($expense['status'] === 'In Progress' ? 'bg-amber-50 text-amber-700 border border-amber-100' :
                        'bg-slate-100 text-slate-500 border border-slate-200') ?>">
                    <span class="w-1.5 h-1.5 rounded-full <?= $expense['status'] === 'Completed' ? 'bg-emerald-500' :
                        ($expense['status'] === 'In Progress' ? 'bg-amber-400' : 'bg-slate-400') ?>"></span>
                    <?= escape_html($expense['status']) ?>
                </span>
            <?php endif; ?>
        </div>
        <div class="flex items-center gap-2">
            <a href="<?= url('/app/couple/budget') ?>" class="cp-btn-back">
                <i class="fa-solid fa-arrow-left"></i> Back
            </a>
            <a href="<?= url("/app/couple/budget/expenses/edit/{$id}") ?>" class="btn btn-secondary btn-sm flex items-center gap-1.5">
                <i class="fa-solid fa-pen text-[10px]"></i> Edit
            </a>
        </div>
    </div>

    <!-- ── Flash Notifications ──────────────────────────────────────────── -->
    <?php if (!empty($success)): ?>
        <div class="p-4 bg-emerald-50 border border-emerald-150 text-emerald-800 rounded-2xl flex items-center gap-3 text-sm shadow-sm">
            <i class="fa-solid fa-circle-check text-emerald-500 text-base flex-shrink-0"></i>
            <div class="font-semibold"><?= escape_html($success) ?></div>
        </div>
    <?php endif; ?>
    <?php if (!empty($error)): ?>
        <div class="p-4 bg-rose-50 border border-rose-150 text-rose-800 rounded-2xl flex items-center gap-3 text-sm shadow-sm">
            <i class="fa-solid fa-circle-xmark text-rose-500 text-base flex-shrink-0"></i>
            <div class="font-semibold"><?= escape_html($error) ?></div>
        </div>
    <?php endif; ?>

    <!-- ── Main Grid: Left (Vendor + Budget + Notes) / Right (Payments) ── -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

        <!-- ── LEFT COLUMN ──────────────────────────────────────────────── -->
        <div class="lg:col-span-2 space-y-5">

            <!-- Budget Summary Card -->
            <div class="bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden">
                <!-- Summary numbers -->
                <div class="grid grid-cols-2 md:grid-cols-4 divide-x divide-slate-100">
                    <div class="p-5">
                        <span class="text-[11px] text-slate-400 font-medium block mb-1">Our Budget</span>
                        <strong class="text-base font-black text-slate-800 leading-tight block"><?= format_money($estCost, $currency) ?></strong>
                    </div>
                    <div class="p-5">
                        <span class="text-[11px] text-slate-400 font-medium block mb-1">Agreed Price</span>
                        <strong class="text-base font-black <?= $actCost > 0 ? 'text-[#A8735C]' : 'text-slate-300' ?> leading-tight block">
                            <?= $actCost > 0 ? format_money($actCost, $currency) : 'Not set' ?>
                        </strong>
                    </div>
                    <div class="p-5">
                        <span class="text-[11px] text-slate-400 font-medium block mb-1">Paid</span>
                        <strong class="text-base font-black text-emerald-600 leading-tight block"><?= format_money($total_paid, $currency) ?></strong>
                    </div>
                    <div class="p-5">
                        <span class="text-[11px] text-slate-400 font-medium block mb-1">Still to Pay</span>
                        <strong class="text-base font-black <?= $isFullyPaid ? 'text-emerald-500' : 'text-slate-800' ?> leading-tight block">
                            <?= $isFullyPaid ? 'Fully Paid ✓' : format_money($remaining_balance, $currency) ?>
                        </strong>
                    </div>
                </div>

                <!-- Payment progress bar -->
                <?php if ($target > 0): ?>
                <div class="px-5 pb-4">
                    <div class="flex justify-between items-center mb-1.5">
                        <span class="text-[11px] text-slate-400 font-medium">Payment Progress</span>
                        <span class="text-[11px] font-bold text-slate-600"><?= number_format($paymentProgress, 0) ?>%</span>
                    </div>
                    <div class="h-2 bg-slate-100 rounded-full overflow-hidden">
                        <div class="h-full rounded-full transition-all duration-500 <?= $isFullyPaid ? 'bg-emerald-500' : 'bg-[#D4A28C]' ?>"
                             style="width: <?= number_format($paymentProgress, 2) ?>%"></div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Next payment due — only if set -->
                <?php if ($hasDueDate): ?>
                <div class="border-t border-slate-50 px-5 py-3 flex items-center gap-2 bg-amber-50/50">
                    <i class="fa-solid fa-calendar-day text-amber-400 text-sm flex-shrink-0"></i>
                    <span class="text-xs text-amber-700 font-medium">Next payment due: <strong><?= $dueDateLabel ?></strong></span>
                </div>
                <?php endif; ?>
            </div>

            <!-- Vendor Card -->
            <div class="bg-white rounded-2xl border border-slate-100 shadow-sm p-5">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="text-sm font-bold text-slate-700">Vendor</h2>
                    <?php if ($hasPhone && $waLink): ?>
                        <a href="<?= $waLink ?>" target="_blank" rel="noopener"
                           class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-emerald-50 hover:bg-emerald-100 border border-emerald-150 text-emerald-700 font-bold text-xs rounded-xl transition-all">
                            <i class="fa-brands fa-whatsapp text-emerald-600"></i> WhatsApp
                        </a>
                    <?php endif; ?>
                </div>

                <?php if ($hasVendor): ?>
                    <div class="flex items-start gap-4">
                        <div class="flex-shrink-0 w-12 h-12 rounded-2xl flex items-center justify-center" style="background-color: var(--brand-ivory-warm); border: 1px solid var(--brand-ivory-dark);">
                            <i class="fa-solid fa-store text-base" style="color: var(--brand-rose-gold);"></i>
                        </div>
                        <div class="flex-1 min-w-0 space-y-1">
                            <strong class="text-sm font-bold text-slate-800 block truncate"><?= escape_html($expense['vendor_name']) ?></strong>
                            <?php if ($hasPic): ?>
                                <div class="flex items-center gap-1.5 text-xs text-slate-500">
                                    <i class="fa-solid fa-user text-slate-300 text-[10px]"></i>
                                    <?= escape_html($expense['vendor_pic']) ?>
                                </div>
                            <?php endif; ?>
                            <?php if ($hasPhone): ?>
                                <div class="flex items-center gap-1.5 text-xs text-slate-500">
                                    <i class="fa-solid fa-phone text-slate-300 text-[10px]"></i>
                                    <?= escape_html($expense['vendor_phone']) ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="flex items-center gap-3 py-2">
                        <div class="w-10 h-10 bg-slate-50 rounded-xl flex items-center justify-center flex-shrink-0">
                            <i class="fa-solid fa-store text-slate-300"></i>
                        </div>
                        <div>
                            <p class="text-sm text-slate-400">No vendor chosen yet</p>
                            <a href="<?= url("/app/couple/budget/expenses/edit/{$id}") ?>" class="link-elegant text-xs font-medium">Add vendor details →</a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Notes Card — only shown when notes exist -->
            <?php if (!empty($expense['notes'])): ?>
            <div class="bg-white rounded-2xl border border-slate-100 shadow-sm p-5">
                <h2 class="text-sm font-bold text-slate-700 mb-3">Notes</h2>
                <p class="text-sm text-slate-600 leading-relaxed whitespace-pre-wrap"><?= escape_html($expense['notes']) ?></p>
            </div>
            <?php endif; ?>

        </div>

        <!-- ── RIGHT COLUMN: Payment History ──────────────────────────── -->
        <div class="lg:col-span-1">
            <div class="bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden">

                <!-- Section header with Log Payment CTA -->
                <div class="px-5 py-4 border-b border-slate-50 flex items-center justify-between">
                    <h2 class="text-sm font-bold text-slate-700">Payments</h2>
                    <button type="button" @click="showPaymentForm = !showPaymentForm" class="btn btn-primary btn-sm flex items-center gap-1.5">
                        <i class="fa-solid" :class="showPaymentForm ? 'fa-minus' : 'fa-plus'"></i>
                        <span x-text="showPaymentForm ? 'Cancel' : 'Log Payment'">Log Payment</span>
                    </button>
                </div>

                <!-- Log Payment Form -->
                <div x-show="showPaymentForm" x-transition class="border-b border-slate-100" style="display: none;">
                    <form method="POST" action="<?= url("/app/couple/budget/expenses/{$id}/payments") ?>" class="p-5 space-y-4">
                        <input type="hidden" name="_csrf" value="<?= escape_html($_SESSION['csrf_token'] ?? '') ?>">

                        <div class="space-y-1.5">
                            <label for="amount" class="form-label">Amount paid</label>
                            <input type="number" step="0.01" min="0.01" id="amount" name="amount" placeholder="e.g. 5000000" class="form-input font-bold" required>
                        </div>

                        <div class="space-y-1.5">
                            <label for="payment_date" class="form-label">Date</label>
                            <input type="date" id="payment_date" name="payment_date" value="<?= date('Y-m-d') ?>" class="form-input" required>
                        </div>

                        <div class="space-y-1.5">
                            <label for="pay_notes" class="form-label">Note <span class="font-normal text-slate-400">(optional)</span></label>
                            <input type="text" id="pay_notes" name="notes" placeholder="e.g. Deposit, Second Installment" class="form-input">
                        </div>

                        <button type="submit" class="btn btn-primary w-full py-2.5 text-xs font-bold shadow-sm">
                            Save Payment
                        </button>
                    </form>
                </div>

                <!-- Payment timeline -->
                <?php if (empty($payments)): ?>
                    <div class="px-5 py-10 text-center">
                        <div class="inline-flex items-center justify-center w-10 h-10 bg-slate-50 rounded-xl mb-3">
                            <i class="fa-solid fa-receipt text-slate-300 text-base"></i>
                        </div>
                        <p class="text-sm text-slate-400 font-medium">No payments yet</p>
                        <p class="text-xs text-slate-300 mt-0.5">Tap "Log Payment" to record one.</p>
                    </div>
                <?php else: ?>
                    <div class="divide-y divide-slate-50">
                        <?php foreach ($payments as $index => $pay): ?>
                            <div class="px-5 py-3.5 flex items-start gap-3 group">
                                <!-- Timeline dot -->
                                <div class="flex-shrink-0 mt-0.5">
                                    <div class="w-7 h-7 rounded-full <?= $index === 0 ? 'bg-emerald-100' : 'bg-slate-100' ?> flex items-center justify-center">
                                        <i class="fa-solid fa-check text-[9px] <?= $index === 0 ? 'text-emerald-600' : 'text-slate-400' ?>"></i>
                                    </div>
                                </div>
                                <!-- Payment info -->
                                <div class="flex-1 min-w-0">
                                    <strong class="text-sm font-bold text-slate-800 block"><?= format_money((float)$pay['amount'], $currency) ?></strong>
                                    <span class="text-[11px] text-slate-400 block mt-0.5">
                                        <?= date('d M Y', strtotime($pay['payment_date'])) ?>
                                        <?php if (!empty($pay['notes'])): ?>
                                            · <?= escape_html($pay['notes']) ?>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                <!-- Delete (subtle, appears on hover) -->
                                <form method="POST" action="<?= url("/app/couple/budget/payments/delete/{$pay['id']}") ?>"
                                      onsubmit="return confirm('Remove this payment record?');" class="flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
                                    <input type="hidden" name="_csrf" value="<?= escape_html($_SESSION['csrf_token'] ?? '') ?>">
                                    <button type="submit" class="w-6 h-6 flex items-center justify-center rounded-lg hover:bg-rose-50 text-slate-300 hover:text-rose-400 transition-all" title="Remove">
                                        <i class="fa-solid fa-trash-can text-[9px]"></i>
                                    </button>
                                </form>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Running total -->
                    <div class="px-5 py-3.5 bg-slate-50 border-t border-slate-100 flex items-center justify-between">
                        <span class="text-xs text-slate-500 font-medium">Total paid</span>
                        <strong class="text-sm font-black text-emerald-600"><?= format_money($total_paid, $currency) ?></strong>
                    </div>
                <?php endif; ?>
            </div>
        </div>

    </div>

</div>
