<?php
/**
 * Couple Portal — Budget Items List Card View (PRI-001)
 * Location: app/views/budget/expenses.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';
?>

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

    <!-- ── Header Section ────────────────────────────────────────────────── -->
    <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>All Items</span>
            </div>
            <h1 class="page-h1">
                <span class="page-header-icon">
                    <i class="fa-solid fa-list-check"></i>
                </span>
                Budget Items
            </h1>
            <p class="page-subtitle">All your wedding budget allocations and expense records.</p>
        </div>
        <div class="flex items-center gap-2.5">
            <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/create') ?>" class="btn btn-primary btn-md">
                <i class="fa-solid fa-plus"></i> Add Item
            </a>
        </div>
    </div>

    <!-- ── Alerts ────────────────────────────────────────────────────────── -->
    <?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-xs shadow-sm">
            <i class="fa-solid fa-circle-check text-emerald-600 text-base"></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-xs shadow-sm">
            <i class="fa-solid fa-circle-xmark text-rose-600 text-base"></i>
            <div class="font-semibold"><?= escape_html($error) ?></div>
        </div>
    <?php endif; ?>

    <!-- ── Filter Card ───────────────────────────────────────────────────── -->
    <div class="bg-white p-5 rounded-3xl border border-slate-100 shadow-sm">
        <form method="GET" action="<?= url('/app/couple/budget/expenses') ?>" class="grid grid-cols-1 md:grid-cols-3 gap-3 items-end">
            <!-- Search -->
            <div class="space-y-1.5">
                <label for="search" class="text-[10px] font-bold uppercase tracking-wider text-slate-400 block">Search Name / Vendor</label>
                <div class="relative">
                    <span class="absolute left-3 top-2 text-slate-400 text-sm"><i class="fa-solid fa-magnifying-glass"></i></span>
                    <input type="text" id="search" name="search" value="<?= escape_html($filters['search'] ?? '') ?>" placeholder="e.g. Catering, Venue..." class="form-input pl-9">
                </div>
            </div>

            <!-- Category -->
            <div class="space-y-1.5">
                <label for="category_id" class="text-[10px] font-bold uppercase tracking-wider text-slate-400 block">Category</label>
                <select id="category_id" name="category_id" class="form-select">
                    <option value="">-- All Categories --</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?= $cat['id'] ?>" <?= (isset($filters['category_id']) && (int)$filters['category_id'] === (int)$cat['id']) ? 'selected' : '' ?>>
                            <?= escape_html($cat['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Actions -->
            <div class="flex gap-2">
                <button type="submit" class="btn btn-primary btn-md flex-grow flex items-center justify-center gap-1.5">
                    <i class="fa-solid fa-filter"></i> Apply Filters
                </button>
                <a href="<?= url('/app/couple/budget/expenses') ?>" class="btn btn-secondary btn-md flex items-center justify-center" title="Clear Filters">
                    Reset
                </a>
            </div>
        </form>
    </div>

    <!-- ── Cards Grid (No tables) ────────────────────────────────────────── -->
    <div class="space-y-4">
        <div class="flex justify-between items-center border-b border-slate-50 pb-2">
            <h3 class="font-extrabold text-slate-700 text-xs uppercase tracking-wider">Active Wedding Items</h3>
            <span class="text-[10px] bg-slate-100 text-slate-600 font-bold px-2 py-0.5 rounded-lg border border-slate-150"><?= $total_expenses ?> Items Found</span>
        </div>

        <?php if (empty($expenses)): ?>
            <div class="bg-white border border-slate-100 rounded-3xl py-12 text-center text-slate-400 text-xs">
                No budget items matching criteria were found.
            </div>
        <?php else: ?>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <?php foreach ($expenses as $item): 
                    $est = (float)$item['estimated_cost'];
                    $act = (float)$item['actual_cost'];
                    $target = $act > 0 ? $act : $est;
                    
                    // Fetch paid amount from database dynamically per item if not present
                    $db = \App\Core\Database::getConnection();
                    $stmtPaid = $db->prepare('SELECT SUM(amount) FROM budget_payments WHERE expense_id = :id AND is_deleted = 0');
                    $stmtPaid->execute(['id' => (int)$item['id']]);
                    $paidAmount = (float)($stmtPaid->fetchColumn() ?: 0.00);

                    $remaining = max(0.00, $target - $paidAmount);
                    $diff = $act > 0 ? ($est - $act) : 0.0;
                ?>
                    <a href="<?= url('/app/couple/budget/expenses/' . $item['id']) ?>" class="bg-white p-5 rounded-3xl border border-slate-100 hover:border-[#D4A28C] hover:shadow-sm transition-all flex flex-col justify-between space-y-4 group">
                        <div class="flex justify-between items-start">
                            <div>
                                <h4 class="text-xs font-black text-slate-800 group-hover:text-[#D4A28C] transition-colors"><?= escape_html($item['name']) ?></h4>
                                <span class="text-[9px] text-slate-450 block mt-0.5">Category: <?= escape_html($item['category_name']) ?></span>
                            </div>
                            <?php if ($item['vendor_name']): ?>
                                <span class="badge badge-secondary text-[9px] font-bold">
                                    <?= escape_html($item['vendor_name']) ?>
                                </span>
                            <?php endif; ?>
                        </div>

                        <div class="grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs">
                            <div>
                                <span class="text-[8px] font-bold uppercase text-slate-400">Planned</span>
                                <strong class="text-slate-700 block mt-0.5"><?= format_money($est, $currency) ?></strong>
                            </div>
                            <div>
                                <span class="text-[8px] font-bold uppercase text-slate-400">Deal Price</span>
                                <strong class="text-slate-805 block mt-0.5"><?= $act > 0 ? format_money($act, $currency) : '—' ?></strong>
                            </div>
                            <div>
                                <span class="text-[8px] font-bold uppercase text-slate-400">Paid</span>
                                <strong class="text-emerald-600 block mt-0.5"><?= format_money($paidAmount, $currency) ?></strong>
                            </div>
                            <div>
                                <span class="text-[8px] font-bold uppercase text-slate-400">Remaining</span>
                                <strong class="text-slate-700 block mt-0.5"><?= format_money($remaining, $currency) ?></strong>
                            </div>
                        </div>

                        <?php if ($act > 0): ?>
                            <div class="flex justify-between items-center text-[9px] border-t border-slate-50 pt-2 text-slate-450">
                                <span>Negotiation Variance</span>
                                <span class="<?= $diff >= 0 ? 'text-emerald-600 font-bold' : 'text-rose-600 font-bold' ?>">
                                    <?= ($diff >= 0 ? 'Saved ' : 'Overby ') . format_money(abs($diff), $currency) ?>
                                </span>
                            </div>
                        <?php endif; ?>
                    </a>
                <?php endforeach; ?>
            </div>

            <!-- Simple Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="flex justify-between items-center text-xs text-slate-400 pt-4">
                    <span>Page <?= $page ?> of <?= $total_pages ?></span>
                    <div class="flex gap-2">
                        <a href="<?= $page > 1 ? url('/app/couple/budget/expenses?page=' . ($page - 1) . '&category_id=' . ($filters['category_id'] ?? '') . '&search=' . urlencode($filters['search'] ?? '')) : '#' ?>" class="px-3 py-1.5 border border-slate-200 rounded-lg hover:bg-slate-50 transition-all font-bold <?= $page <= 1 ? 'opacity-50 pointer-events-none' : '' ?>">Previous</a>
                        <a href="<?= $page < $total_pages ? url('/app/couple/budget/expenses?page=' . ($page + 1) . '&category_id=' . ($filters['category_id'] ?? '') . '&search=' . urlencode($filters['search'] ?? '')) : '#' ?>" class="px-3 py-1.5 border border-slate-200 rounded-lg hover:bg-slate-50 transition-all font-bold <?= $page >= $total_pages ? 'opacity-50 pointer-events-none' : '' ?>">Next</a>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

</div>
