<?php
/**
 * Couple Portal — Budget Planner Homepage (PRI-002 / UX006)
 * Location: app/views/budget/dashboard.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, '.', ',');
    }
}

$currency        = $summary['currency'] ?? 'IDR';
$totalBudget     = (float) $summary['total_budget'];
$totalPlanned    = (float) $summary['total_planned'];
$totalActual     = (float) $summary['total_actual'];
$totalPaid       = (float) $summary['total_paid'];
$remainingBudget = (float) $summary['remaining_budget'];
$remainingToPay  = (float) $summary['remaining_to_pay'];

// Overall savings vs. original estimates (only from categories that have a signed vendor)
$overallDifference = 0.0;
foreach ($category_stats as $c) {
    if ($c['actual'] > 0) {
        $overallDifference += ($c['planned'] - $c['actual']);
    }
}

// Global payment progress (paid vs. total committed)
$commitBase    = $totalActual > 0 ? $totalActual : $totalPlanned;
$paidPercent   = $commitBase > 0 ? min(100, ($totalPaid / $commitBase) * 100) : 0;
$budgetPercent = $totalBudget > 0 ? min(100, ($commitBase / $totalBudget) * 100) : 0;
?>

<div class="max-w-6xl mx-auto space-y-8">

    <!-- ── Page Header ──────────────────────────────────────────────────── -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
            <h1 class="text-2xl font-black tracking-tight text-slate-800 flex items-center gap-2.5">
                <span class="page-header-icon">
                    <i class="fa-solid fa-wallet"></i>
                </span>
                Budget Planner
            </h1>
            <p class="text-sm text-slate-500 mt-1.5 ml-0.5">Track your wedding spending — from first estimate to final payment.</p>
        </div>
        <div>
            <a href="<?= url('/app/couple/budget/settings') ?>"
               class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 text-slate-600 text-xs font-semibold shadow-sm transition-all" onmouseover="this.style.color='#232323'" onmouseout="this.style.color=''">
                <i class="fa-solid fa-sliders text-slate-400 text-xs"></i> Budget Setup
            </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; ?>

    <!-- ── Hero Summary ─────────────────────────────────────────────────── -->
    <div class="rounded-3xl overflow-hidden shadow-sm" style="border:1px solid #E8DDD0;">

        <!-- DS001: Charcoal hero band -->
        <div class="px-8 py-10 md:py-12 text-white relative overflow-hidden" style="background-color:#232323;">
            <div class="absolute -right-16 -top-16 w-64 h-64 rounded-full pointer-events-none" style="background:rgba(212,162,140,0.06); filter:blur(40px);"></div>
            <div class="absolute -left-10 -bottom-10 w-48 h-48 rounded-full pointer-events-none" style="background:rgba(212,162,140,0.04); filter:blur(32px);"></div>

            <div class="grid grid-cols-2 md:grid-cols-4 gap-8 relative">
                <!-- Our Budget — primary -->
                <div>
                    <span class="text-[11px] font-semibold uppercase tracking-widest block mb-2" style="color:#D0C8BE;">Our Budget</span>
                    <strong class="text-3xl font-black text-white leading-none block">
                        <?= format_money($totalBudget, $currency) ?>
                    </strong>
                </div>

                <!-- Committed -->
                <div>
                    <span class="text-[11px] font-semibold uppercase tracking-widest block mb-2" style="color:#D0C8BE;">Committed</span>
                    <strong class="text-3xl font-black leading-none block" style="color:#E8DDD0;">
                        <?= format_money($commitBase, $currency) ?>
                    </strong>
                </div>

                <!-- Paid So Far -->
                <div>
                    <span class="text-[11px] font-semibold uppercase tracking-widest block mb-2" style="color:#D0C8BE;">Paid So Far</span>
                    <strong class="text-3xl font-black text-emerald-300 leading-none block">
                        <?= format_money($totalPaid, $currency) ?>
                    </strong>
                </div>

                <!-- Still to Pay -->
                <div>
                    <span class="text-[11px] font-semibold uppercase tracking-widest block mb-2" style="color:#D0C8BE;">Still to Pay</span>
                    <strong class="text-3xl font-black text-white leading-none block">
                        <?= format_money($remainingToPay, $currency) ?>
                    </strong>
                </div>
            </div>
        </div>

        <!-- Progress bars band -->
        <div class="bg-white px-8 py-5 grid grid-cols-1 md:grid-cols-2 gap-6">

            <!-- Budget Used -->
            <div>
                <div class="flex justify-between items-baseline mb-2">
                    <span class="text-xs font-semibold text-slate-500">Budget Used</span>
                    <span class="text-sm font-black text-slate-800"><?= number_format($budgetPercent, 0) ?>%</span>
                </div>
                <div class="h-2.5 bg-slate-100 rounded-full overflow-hidden">
                    <div class="h-full rounded-full transition-all duration-500 <?= $budgetPercent > 90 ? 'bg-rose-400' : ($budgetPercent > 75 ? 'bg-amber-400' : 'bg-[#D4A28C]') ?>"
                         style="width: <?= number_format(min(100, $budgetPercent), 2) ?>%"></div>
                </div>
                <p class="text-[11px] text-slate-400 mt-1.5">
                    <?= format_money($commitBase, $currency) ?> of <?= format_money($totalBudget, $currency) ?>
                </p>
            </div>

            <!-- Payments Made -->
            <div>
                <div class="flex justify-between items-baseline mb-2">
                    <span class="text-xs font-semibold text-slate-500">Payments Made</span>
                    <span class="text-sm font-black text-slate-800"><?= number_format($paidPercent, 0) ?>%</span>
                </div>
                <div class="h-2.5 bg-slate-100 rounded-full overflow-hidden">
                    <div class="h-full bg-emerald-500 rounded-full transition-all duration-500"
                         style="width: <?= number_format(min(100, $paidPercent), 2) ?>%"></div>
                </div>
                <p class="text-[11px] text-slate-400 mt-1.5">
                    <?= format_money($totalPaid, $currency) ?> of <?= format_money($commitBase, $currency) ?>
                </p>
            </div>
        </div>

        <!-- Savings indicator — only when vendors are signed -->
        <?php if ($totalActual > 0): ?>
        <div class="border-t border-slate-100 bg-slate-50/60 px-8 py-3 flex items-center justify-between">
            <span class="text-xs text-slate-400 font-medium">vs. original estimates</span>
            <span class="text-xs font-bold <?= $overallDifference >= 0 ? 'text-emerald-600' : 'text-rose-500' ?>">
                <?php if ($overallDifference > 0): ?>
                    <i class="fa-solid fa-arrow-down text-emerald-500 mr-1"></i>
                    Saved <?= format_money($overallDifference, $currency) ?>
                <?php elseif ($overallDifference < 0): ?>
                    <i class="fa-solid fa-arrow-up text-rose-500 mr-1"></i>
                    <?= format_money(abs($overallDifference), $currency) ?> over estimate
                <?php else: ?>
                    <i class="fa-solid fa-circle-check text-emerald-500 mr-1"></i>
                    Right on budget
                <?php endif; ?>
            </span>
        </div>
        <?php endif; ?>

    </div>

    <!-- ── Category Cards ───────────────────────────────────────────────── -->
    <?php if (empty($category_stats)): ?>

        <!-- Empty State -->
        <div class="empty-state-elegant">
            <div class="empty-state-icon">
                <i class="fa-solid fa-tags"></i>
            </div>
            <h3 class="empty-state-title">No categories yet</h3>
            <p class="empty-state-text">Set up your wedding budget to get started.</p>
            <a href="<?= url('/app/couple/budget/settings') ?>" class="btn btn-primary btn-md">
                <i class="fa-solid fa-sliders"></i> Set Up Budget
            </a>
        </div>

    <?php else: ?>

        <div>
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xs font-bold text-slate-400 uppercase tracking-wider">Wedding Categories</h2>
                <span class="text-xs text-slate-400"><?= count($category_stats) ?> categories</span>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <?php foreach ($category_stats as $cat):
                    $catId     = (int) $cat['category_id'];
                    $target    = $cat['actual'] > 0 ? $cat['actual'] : $cat['planned'];
                    $remaining = max(0.00, $target - $cat['paid']);
                    $progress  = $target > 0 ? min(100, ($cat['paid'] / $target) * 100) : 0.0;
                    $hasVendor = !empty($cat['vendor_name']) && $cat['vendor_name'] !== '—';
                    $hasActual = $cat['actual'] > 0;

                    // Status
                    if ($remaining <= 0 && $target > 0) {
                        $statusDot   = 'bg-emerald-400';
                        $statusLabel = 'Fully Paid';
                        $statusColor = 'text-emerald-600';
                    } elseif ($cat['paid'] > 0) {
                        $statusDot   = 'bg-amber-400';
                        $statusLabel = 'In Progress';
                        $statusColor = 'text-amber-600';
                    } elseif ($hasVendor) {
                        $statusDot   = 'bg-[#D4A28C]';
                        $statusLabel = 'Vendor Chosen';
                        $statusColor = 'text-[#A8735C]';
                    } else {
                        $statusDot   = 'bg-slate-300';
                        $statusLabel = 'Not Started';
                        $statusColor = 'text-slate-400';
                    }

                    // Progress bar colour
                    $barColor = $progress >= 100 ? 'bg-emerald-500' : ($progress > 0 ? 'bg-[#D4A28C]' : 'bg-slate-200');
                ?>
                    <a href="<?= url('/app/couple/budget/category/' . $catId) ?>"
                       class="group bg-white rounded-2xl border border-slate-100 hover:border-[#D4A28C] hover:shadow-md transition-all p-5 flex flex-col gap-3">

                        <!-- Card Header -->
                        <div class="flex items-start justify-between gap-2">
                            <div class="flex-1 min-w-0">
                                <h3 class="text-sm font-bold text-slate-800 group-hover:text-[#D4A28C] transition-colors truncate leading-tight">
                                    <?= escape_html($cat['category_name']) ?>
                                </h3>
                                <div class="flex items-center gap-1.5 mt-1.5">
                                    <span class="inline-block w-1.5 h-1.5 rounded-full flex-shrink-0 <?= $statusDot ?>"></span>
                                    <span class="text-[11px] font-medium <?= $statusColor ?>"><?= $statusLabel ?></span>
                                </div>
                            </div>
                            <i class="fa-solid fa-chevron-right text-slate-300 group-hover:text-[#D4A28C] text-xs mt-0.5 transition-colors flex-shrink-0"></i>
                        </div>

                        <!-- Progress bar (always shown — empty bar for not-started) -->
                        <div>
                            <div class="h-1.5 bg-slate-100 rounded-full overflow-hidden">
                                <div class="h-full rounded-full transition-all duration-500 <?= $barColor ?>"
                                     style="width: <?= number_format($progress, 2) ?>%"></div>
                            </div>
                            <?php if ($target > 0): ?>
                                <div class="flex items-center justify-between mt-1.5">
                                    <span class="text-[11px] text-slate-400">
                                        <?= number_format($progress, 0) ?>% paid
                                    </span>
                                    <span class="text-[11px] font-semibold <?= $remaining <= 0 ? 'text-emerald-600' : 'text-slate-500' ?>">
                                        <?= $remaining <= 0 ? 'Complete' : format_money($remaining, $currency) . ' left' ?>
                                    </span>
                                </div>
                            <?php else: ?>
                                <p class="text-[11px] text-slate-300 mt-1.5">No budget set</p>
                            <?php endif; ?>
                        </div>

                        <!-- Financials: Budget + Paid (compact 2-col) -->
                        <div class="grid grid-cols-2 gap-3 pt-2 border-t border-slate-50 text-xs">
                            <div>
                                <span class="text-[10px] text-slate-400 font-medium block">Budget</span>
                                <strong class="text-slate-700 block mt-0.5"><?= format_money($cat['planned'], $currency) ?></strong>
                            </div>
                            <div>
                                <span class="text-[10px] text-slate-400 font-medium block">Paid</span>
                                <strong class="<?= $cat['paid'] > 0 ? 'text-emerald-600' : 'text-slate-400' ?> block mt-0.5">
                                    <?= format_money($cat['paid'], $currency) ?>
                                </strong>
                            </div>
                        </div>

                        <!-- Vendor row — only if assigned -->
                        <?php if ($hasVendor): ?>
                            <div class="border-t border-slate-50 pt-2 flex items-center gap-1.5">
                                <i class="fa-solid fa-store text-slate-300 text-[10px] flex-shrink-0"></i>
                                <span class="text-[11px] text-slate-500 font-medium truncate"><?= escape_html($cat['vendor_name']) ?></span>
                            </div>
                        <?php endif; ?>

                    </a>
                <?php endforeach; ?>
            </div>
        </div>

    <?php endif; ?>

</div>
