<?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();
$adminId = (int)($user['user_id'] ?? 0);
$title = 'Complaint';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    http_response_code(400);
    echo 'Invalid ID';
    exit;
}

$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],
];

$error = '';
$row = null;

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

    $stmt = $pdo->prepare(
        "SELECT c.complaint_id, c.customer_id, c.task_id, c.complaint_type, c.subject, c.description,
                c.status, c.resolution_notes, c.resolved_by, c.created_at, c.resolved_at,
                u.full_name AS customer_name, u.email AS customer_email
         FROM complaints c
         JOIN users u ON c.customer_id = u.user_id
         WHERE c.complaint_id = :id
         LIMIT 1"
    );
    $stmt->execute(['id' => $id]);
    $row = $stmt->fetch();

    if (!$row) {
        http_response_code(404);
        echo 'Complaint not found';
        exit;
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$values = [
    'status' => (string)($row['status'] ?? 'pending'),
    'resolution_notes' => (string)($row['resolution_notes'] ?? ''),
];

$allowedStatuses = ['pending', 'in_review', 'resolved', 'closed'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $values['status'] = trim((string)($_POST['status'] ?? ''));
    $values['resolution_notes'] = trim((string)($_POST['resolution_notes'] ?? ''));

    if (!in_array($values['status'], $allowedStatuses, true)) {
        $error = 'Invalid status.';
    } else {
        try {
            $pdo = Database::pdo();

            $resolvedAt = null;
            $resolvedBy = null;

            if (in_array($values['status'], ['resolved', 'closed'], true)) {
                $resolvedAt = date('Y-m-d H:i:s');
                $resolvedBy = $adminId;
            }

            $stmtU = $pdo->prepare(
                "UPDATE complaints
                 SET status = :status,
                     resolution_notes = :resolution_notes,
                     resolved_by = :resolved_by,
                     resolved_at = :resolved_at
                 WHERE complaint_id = :id"
            );
            $stmtU->execute([
                'status' => $values['status'],
                'resolution_notes' => ($values['resolution_notes'] !== '' ? $values['resolution_notes'] : null),
                'resolved_by' => $resolvedBy,
                'resolved_at' => $resolvedAt,
                'id' => $id,
            ]);

            header('Location: /pest/public/admin/complaints.php');
            exit;
        } catch (Throwable $e) {
            $error = $e->getMessage();
        }
    }
}

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">Complaint #<?= e((string)$row['complaint_id']) ?></h1>
            <p class="mt-1 text-sm text-slate-600">Customer: <span class="font-medium"><?= e((string)$row['customer_name']) ?></span> (<?= e((string)$row['customer_email']) ?>)</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/complaints.php">Back</a>
    </div>

    <div class="mt-6 grid grid-cols-1 gap-6 lg:grid-cols-2">
        <div class="rounded-xl border bg-slate-50 p-4">
            <div class="text-xs font-medium text-slate-600">Details</div>
            <div class="mt-2 text-sm">
                <div><span class="text-slate-500">Type:</span> <span class="font-medium"><?= e((string)$row['complaint_type']) ?></span></div>
                <div class="mt-1"><span class="text-slate-500">Task ID:</span> <span class="font-medium"><?= e((string)($row['task_id'] ?? '')) ?></span></div>
                <div class="mt-1"><span class="text-slate-500">Created:</span> <span class="font-medium"><?= e((string)$row['created_at']) ?></span></div>
                <div class="mt-4">
                    <div class="text-xs font-medium text-slate-600">Subject</div>
                    <div class="mt-1 font-medium"><?= e((string)$row['subject']) ?></div>
                </div>
                <div class="mt-4">
                    <div class="text-xs font-medium text-slate-600">Description</div>
                    <div class="mt-1 whitespace-pre-wrap"><?= e((string)$row['description']) ?></div>
                </div>
            </div>
        </div>

        <div class="rounded-xl border bg-white p-4">
            <div class="text-xs font-medium text-slate-600">Response</div>

            <form class="mt-3 space-y-4" method="post" action="">
                <div>
                    <label class="block text-sm font-medium">Status</label>
                    <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="status">
                        <?php foreach ($allowedStatuses as $st): ?>
                            <option value="<?= e($st) ?>" <?= ($values['status'] === $st) ? 'selected' : '' ?>><?= e($st) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <div class="mt-1 text-xs text-slate-500">Use <span class="font-medium">in_review</span> to open complaint, and <span class="font-medium">closed</span> to close it.</div>
                </div>

                <div>
                    <label class="block text-sm font-medium">Resolution / Notes</label>
                    <textarea class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="resolution_notes" rows="6" placeholder="Write your response..."><?= e($values['resolution_notes']) ?></textarea>
                </div>

                <button class="w-full rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" type="submit">Save</button>
            </form>

            <div class="mt-4 text-xs text-slate-500">
                <?php if (!empty($row['resolved_at'])): ?>
                    Resolved at: <span class="font-medium"><?= e((string)$row['resolved_at']) ?></span>
                <?php else: ?>
                    Not resolved yet.
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php
$content = ob_get_clean();
require __DIR__ . '/../../includes/dashboard_layout.php';
