<?php

declare(strict_types=1);

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

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

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

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

$rows = [];
$error = '';

try {
    $pdo = Database::pdo();
    $rows = $pdo->query(
        "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,
            u.full_name AS customer_name,
            u.email AS customer_email,
            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 users u ON p.customer_id = u.user_id
         JOIN services s ON sr.service_id = s.service_id
         WHERE 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"
    )->fetchAll();
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => '/pest/public/admin/customers.php', 'active' => false],
    ['label' => 'Staff', 'href' => '/pest/public/admin/staff.php', 'active' => false],
    ['label' => 'Staff Locations', 'href' => '/pest/public/admin/staff_locations.php', 'active' => false],
    ['label' => 'Services', 'href' => '/pest/public/admin/services.php', 'active' => false],
    ['label' => 'Task Assignment', 'href' => '/pest/public/admin/task_assignment.php', 'active' => false],
    ['label' => 'Payments', 'href' => '/pest/public/admin/payments.php', 'active' => true],
    ['label' => 'Complaints', 'href' => '/pest/public/admin/complaints.php', 'active' => false],
    ['label' => 'Reports', 'href' => '/pest/public/admin/reports.php', 'active' => false],
];

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">Completed</span>. Pending are listed first by oldest due date.</p>
        </div>
    </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">Customer</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="7">No payments found.</td></tr>
                <?php else: ?>
                    <?php foreach ($rows as $r): ?>
                        <?php
                            $status = (string)$r['payment_status'];
                            $isCompleted = ($status === 'completed');
                            $daysOverdue = (int)($r['days_overdue'] ?? 0);
                            $ageLabel = $isCompleted
                                ? '-'
                                : ($daysOverdue > 0 ? ($daysOverdue . ' days overdue') : (abs($daysOverdue) . ' days left'));

                            $badge = $isCompleted
                                ? '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');
                        ?>
                        <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">
                                <div class="font-medium"><?= e((string)$r['customer_name']) ?></div>
                                <div class="text-xs text-slate-500"><?= e((string)$r['customer_email']) ?></div>
                            </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($status) ?>
                                </span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
$content = ob_get_clean();

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