<?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 = 'Complaints';

$status = (string)($_GET['status'] ?? 'open');
$q = trim((string)($_GET['q'] ?? ''));

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

$allowed = ['open', 'closed', 'all'];
if (!in_array($status, $allowed, true)) {
    $status = 'open';
}

try {
    $pdo = Database::pdo();

    $where = [];
    $params = [];

    if ($status === 'open') {
        $where[] = "c.status IN ('pending','in_review')";
    } elseif ($status === 'closed') {
        $where[] = "c.status IN ('resolved','closed')";
    }

    if ($q !== '') {
        $where[] = '(c.subject LIKE :q OR c.description LIKE :q OR u.full_name LIKE :q)';
        $params['q'] = '%' . $q . '%';
    }

    $sql =
        "SELECT c.complaint_id, c.complaint_type, c.subject, c.status, c.created_at, c.task_id,
                u.full_name AS customer_name, u.email AS customer_email
         FROM complaints c
         JOIN users u ON c.customer_id = u.user_id";

    if ($where) {
        $sql .= ' WHERE ' . implode(' AND ', $where);
    }

    $sql .= ' ORDER BY c.created_at DESC';

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->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' => false],
    ['label' => 'Complaints', 'href' => '/pest/public/admin/complaints.php', 'active' => true],
    ['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 flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-xl font-semibold">Complaints</h1>
            <p class="mt-1 text-sm text-slate-600">View customer complaints and respond / close.</p>
        </div>
    </div>

    <form class="mt-5 grid grid-cols-1 gap-2 sm:grid-cols-[160px_1fr_auto_auto]" method="get" action="">
        <select class="rounded-lg border px-3 py-2 text-sm" name="status">
            <option value="open" <?= ($status === 'open') ? 'selected' : '' ?>>Open</option>
            <option value="closed" <?= ($status === 'closed') ? 'selected' : '' ?>>Closed</option>
            <option value="all" <?= ($status === 'all') ? 'selected' : '' ?>>All</option>
        </select>
        <input class="rounded-lg border px-3 py-2 text-sm" type="text" name="q" value="<?= e($q) ?>" placeholder="Search subject, description, customer">
        <button class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" type="submit">Filter</button>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/complaints.php">Reset</a>
    </form>

    <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">ID</th>
                    <th class="py-2 pr-4">Customer</th>
                    <th class="py-2 pr-4">Subject</th>
                    <th class="py-2 pr-4">Type</th>
                    <th class="py-2 pr-4">Task</th>
                    <th class="py-2 pr-4">Status</th>
                    <th class="py-2">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!$rows): ?>
                    <tr class="border-b"><td class="py-3 text-slate-500" colspan="7">No complaints found.</td></tr>
                <?php else: ?>
                    <?php foreach ($rows as $r): ?>
                        <tr class="border-b last:border-0">
                            <td class="py-3 pr-4 font-medium">#<?= e((string)$r['complaint_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['subject']) ?></td>
                            <td class="py-3 pr-4"><?= e((string)$r['complaint_type']) ?></td>
                            <td class="py-3 pr-4"><?= e((string)($r['task_id'] ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= e((string)$r['status']) ?></td>
                            <td class="py-3">
                                <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="/pest/public/admin/complaint_edit.php?id=<?= e((string)$r['complaint_id']) ?>">Open</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
$content = ob_get_clean();

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