<?php

declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';

$config = require __DIR__ . '/../../config/config.php';

auth_start_session();
auth_require_role(['customer']);

header('Location: ' . Constants::APP_ROOT . '/customer/index.php');
exit;

$user = auth_user();
$title = 'Payments';

$customerId = (int)($user['user_id'] ?? 0);
$rows = [];
$error = '';

try {
    $pdo = Database::pdo();
    $stmt = $pdo->prepare(
        "SELECT
            p.payment_id,
            p.request_id,
            p.amount,
            p.payment_method,
            p.transaction_id,
            p.payment_status,
            p.due_date,
            p.payment_received_at,
            s.service_name,
            sr.preferred_date,
            sr.status AS request_status,
            DATEDIFF(CURDATE(), p.due_date) AS days_overdue
         FROM payments p
         JOIN service_requests sr ON p.request_id = sr.request_id
         JOIN services s ON sr.service_id = s.service_id
         WHERE p.customer_id = :customer_id
           AND p.payment_status IN ('pending','processing','completed')
         ORDER BY
            CASE WHEN p.payment_status = 'completed' THEN 1 ELSE 0 END ASC,
            CASE WHEN p.payment_status = 'completed' THEN NULL ELSE p.due_date END ASC,
            CASE WHEN p.payment_status = 'completed' THEN p.payment_received_at END DESC"
    );
    $stmt->execute(['customer_id' => $customerId]);
    $rows = $stmt->fetchAll();
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/customer/overview.php', 'active' => false],
    ['label' => 'My Requests', 'href' => '/pest/public/customer/index.php', 'active' => false],
    ['label' => 'Request Service', 'href' => '/pest/public/customer/request_service.php', 'active' => false],
    ['label' => 'My Services', 'href' => '/pest/public/customer/my_services.php', 'active' => false],
    ['label' => 'Service Reports', 'href' => '/pest/public/customer/reports.php', 'active' => false],
    ['label' => 'IPM Map', 'href' => '/pest/public/customer/ipm_map.php', 'active' => false],
    ['label' => 'Gap Analysis Report', 'href' => '/pest/public/customer/gap_analysis_report.php', 'active' => false],
    ['label' => 'Trend Analysis Report', 'href' => '/pest/public/customer/trend_analysis_report.php', 'active' => false],
    ['label' => 'Complaints', 'href' => '/pest/public/customer/complaints.php', 'active' => false],
    ['label' => 'Payments', 'href' => '/pest/public/customer/payments.php', 'active' => true],
];

ob_start();
?>
<?php if ($error !== ''): ?>
    <div class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
        <?= e($error) ?>
    </div>
<?php endif; ?>

<div class="rounded-xl border bg-white p-6">
    <div class="flex items-start justify-between gap-4">
        <div>
            <h1 class="text-xl font-semibold">Payments</h1>
            <p class="mt-1 text-sm text-slate-600">Showing <span class="font-medium">Pending/Processing</span> and <span class="font-medium">Paid</span>. Pending are shown first by oldest due date.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/customer/index.php">Back</a>
    </div>

    <div class="mt-5 overflow-x-auto">
        <table class="min-w-full text-sm">
            <thead class="text-left text-slate-600">
                <tr class="border-b">
                    <th class="py-2 pr-4">Payment</th>
                    <th class="py-2 pr-4">Service</th>
                    <th class="py-2 pr-4">Due</th>
                    <th class="py-2 pr-4">Age</th>
                    <th class="py-2">Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!$rows): ?>
                    <tr class="border-b"><td class="py-3 text-slate-500" colspan="6">No payments found.</td></tr>
                <?php else: ?>
                    <?php foreach ($rows as $r): ?>
                        <?php
                            $status = (string)$r['payment_status'];
                            $isPaid = ($status === 'completed');
                            $daysOverdue = (int)($r['days_overdue'] ?? 0);
                            $ageLabel = $isPaid
                                ? '-'
                                : ($daysOverdue > 0 ? ($daysOverdue . ' days overdue') : (abs($daysOverdue) . ' days left'));

                            $badge = $isPaid
                                ? 'bg-green-50 text-green-700 border-green-200'
                                : (($status === 'processing') ? 'bg-amber-50 text-amber-700 border-amber-200' : 'bg-indigo-50 text-indigo-700 border-indigo-200');

                            $label = $isPaid ? 'paid' : $status;
                        ?>
                        <tr class="border-b last:border-0">
                            <td class="py-3 pr-4 font-medium">#<?= e((string)$r['payment_id']) ?></td>
                            <td class="py-3 pr-4"><?= e((string)$r['service_name']) ?></td>
                            <td class="py-3 pr-4"><?= e((string)$r['due_date']) ?></td>
                            <td class="py-3 pr-4"><?= e($ageLabel) ?></td>
                            <td class="py-3">
                                <span class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-medium <?= e($badge) ?>">
                                    <?= e($label) ?>
                                </span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
$content = ob_get_clean();

require __DIR__ . '/../../includes/dashboard_layout.php';
