<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/notifications.php';
require_once __DIR__ . '/../includes/payments.php';
require_customer();

$uid = (int)$_SESSION['user']['id'];
$status = $_GET['status'] ?? ''; 
$method = $_GET['method'] ?? '';

// Custom query to get total spent
$spent = $pdo->prepare("SELECT SUM(amount) FROM payments WHERE application_id IN (SELECT id FROM applications WHERE user_id=?) AND status='confirmed'");
$spent->execute([$uid]);
$totalSpent = (float)$spent->fetchColumn();

// List payments
$sql = "SELECT p.*, s.service_name 
        FROM payments p 
        JOIN applications a ON p.application_id = a.id 
        JOIN services s ON a.service_id = s.id 
        WHERE a.user_id = ?";
$params = [$uid];

if ($status) { $sql .= " AND p.status = ?"; $params[] = $status; }
if ($method) { $sql .= " AND p.method = ?"; $params[] = $method; }

$sql .= " ORDER BY p.created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<style>
/* Customer Payments Styles */
.customer-header { display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 32px; gap: 20px; flex-wrap: wrap; }
.customer-title { margin: 0; font-size: 28px; font-weight: 800; color: var(--text); letter-spacing: -0.5px; }

/* KPI Card (reusing from referrals) */
.kpi-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
}
.kpi-card.currency-card {
    flex-direction: row;
    align-items: center;
    gap: 16px;
}
.kpi-currency-icon {
    width: 56px; /* Slightly larger for this card */
    height: 56px;
    border-radius: 16px;
    background: #eff6ff;
    color: var(--primary);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    font-weight: 700;
}
.kpi-label {
    font-size: 13px;
    color: var(--muted);
    font-weight: 700; /* Changed to 700 for consistency */
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 4px;
}
.kpi-value {
    font-size: 28px;
    font-weight: 800;
    color: var(--text);
    line-height: 1;
}

/* Filter & Table */
.history-card { background: #fff; border: 1px solid var(--border); border-radius: 24px; overflow: hidden; }
.history-header { padding: 24px 32px; border-bottom: 1px solid var(--border); background: #f8fafc; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px; }

.ref-tag { font-family: monospace; font-size: 12px; font-weight: 600; color: var(--muted); background: #f1f5f9; padding: 2px 6px; border-radius: 4px; }

.history-header form {
    display: flex;
    gap: 12px;
    align-items: center;
}

@media(max-width:767px){
    .history-header {
        flex-direction: column;
        align-items: stretch;
    }
    .history-header form {
        flex-direction: column;
        align-items: stretch;
    }
    .history-header form select, .history-header form button {
        width: 100%;
        justify-content: center;
    }
    .table-wrap { display: none; }
    .mobile-grid { display: grid; }
}
@media(min-width:768px){
  .mobile-grid { display: none; }
}
.chip {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 700;
    text-transform: capitalize;
}
.chip-pending { background: #fff7ed; color: #ea580c; }
.chip-confirmed { background: #f0fdf4; color: #16a34a; }
.chip-failed { background: #fef2f2; color: #ef4444; }
</style>

<div class="customer-header">
    <div>
        <h1 class="customer-title">Payment History</h1>
        <p style="margin:4px 0 0; color:var(--muted); font-size:15px">Keep track of all your service transactions and receipts.</p>
    </div>
    <div class="kpi-card currency-card">
        <div class="kpi-currency-icon">₦</div>
        <div>
            <div class="kpi-label">Lifetime Investment</div>
            <div class="kpi-value">₦<?=number_format($totalSpent, 2)?></div>
        </div>
    </div>
</div>

<div class="history-card">
    <div class="history-header">
        <form method="get" style="display:flex; gap:12px; align-items:center">
            <select name="status" class="form-select" style="margin-bottom:0; min-width:160px">
                <option value="">All Statuses</option>
                <option value="pending" <?=$status==='pending'?'selected':''?>>Pending</option>
                <option value="confirmed" <?=$status==='confirmed'?'selected':''?>>Confirmed</option>
                <option value="failed" <?=$status==='failed'?'selected':''?>>Failed</option>
            </select>
            <button class="btn primary" style="padding:10px 20px; font-weight:700">Filter</button>
            <?php if($status): ?><a href="?" class="btn" style="padding:10px 20px">Clear</a><?php endif; ?>
        </form>
        
        <a href="/api/payments.php?export=csv" class="btn btn-outline" style="padding:10px 20px; font-weight:600">
            <?=ui_icon('download', 18)?> Export CSV
        </a>
    </div>

    <div class="table-wrap">
        <table class="striped">
            <thead>
                <tr>
                    <th style="padding-left:32px">Date</th>
                    <th>Service Description</th>
                    <th>Reference</th>
                    <th>Method</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th style="padding-right:32px; text-align:right">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $r): ?>
                <tr>
                    <td style="padding-left:32px">
                        <div style="font-weight:600; font-size:14px"><?=date('M j, Y', strtotime($r['created_at']))?></div>
                        <div style="font-size:12px; color:var(--muted)"><?=date('H:i', strtotime($r['created_at']))?></div>
                    </td>
                    <td>
                        <div style="font-weight:700; color:var(--text)"><?=e($r['service_name'])?></div>
                        <div style="font-size:12px; color:var(--muted)">Application #<?=e((string)$r['application_id'])?></div>
                    </td>
                    <td><span class="ref-tag"><?=e($r['payment_reference'])?></span></td>
                    <td>
                        <span class="badge" style="text-transform:uppercase; font-size:11px; font-weight:700"><?=e($r['method'] ?: 'bank')?></span>
                    </td>
                    <td>
                        <div style="font-weight:800; color:var(--text); font-size:16px">₦<?=number_format((float)$r['amount'], 2)?></div>
                    </td>
                    <td>
                        <?php 
                        $st = $r['status'];
                        $cls = 'chip-pending'; 
                        if($st=='confirmed') $cls='chip-confirmed'; 
                        if($st=='failed') $cls='chip-failed'; 
                        ?>
                        <span class="chip <?=$cls?>"><?=ucfirst($st)?></span>
                    </td>
                    <td style="padding-right:32px; text-align:right">
                        <a href="/customer/view_application.php?id=<?=e((string)$r['application_id'])?>" class="btn" style="padding:8px 16px; font-size:13px; font-weight:600">
                            View Details
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
                
                <?php if (empty($rows)): ?>
                <tr>
                    <td colspan="7" style="text-align:center; padding:80px; color:var(--muted)">
                        No payment records found.
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <div class="mobile-grid">
        <?php foreach ($rows as $r): ?>
            <?php 
            $st = $r['status'];
            $cls = 'chip-pending'; 
            if($st=='confirmed') $cls='chip-confirmed'; 
            if($st=='failed') $cls='chip-failed'; 
            ?>
            <div class="card" style="margin-bottom:0; padding:20px; border-radius:16px">
                <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:16px">
                    <div>
                        <div style="font-weight:700; color:var(--text)"><?=e($r['service_name'])?></div>
                        <div style="font-size:13px; color:var(--muted)">Application #<?=e((string)$r['application_id'])?></div>
                    </div>
                    <span class="chip <?=$cls?>"><?=ucfirst($st)?></span>
                </div>
                <div style="font-size:13px; color:var(--muted); margin-bottom:4px">Ref: <span class="ref-tag" style="background:none; padding:0"><?=e($r['payment_reference'])?></span></div>
                <div style="font-size:13px; color:var(--muted); margin-bottom:16px">Method: <span class="badge" style="text-transform:uppercase; font-size:11px; font-weight:700"><?=e($r['method'] ?: 'bank')?></span></div>
                <div style="display:flex; justify-content:space-between; align-items:center; margin-top:8px; border-top:1px solid #f1f5f9; padding-top:12px">
                    <div style="font-weight:800; color:var(--text); font-size:16px">₦<?=number_format((float)$r['amount'], 2)?></div>
                    <a href="/customer/view_application.php?id=<?=e((string)$r['application_id'])?>" class="btn" style="padding:6px 12px; font-size:12px; font-weight:600">
                        View Details
                    </a>
                </div>
            </div>
        <?php endforeach; ?>
        <?php if (empty($rows)): ?>
            <div class="card" style="text-align:center; padding:40px; color:var(--muted)">
                No payment records found.
            </div>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
