<?php
/// file: app/Controllers/Admin/ContactAdminController.php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Response;

final class ContactAdminController extends Controller
{
    public function index(Request $request): Response
    {
        $pdo = $this->app->pdo();
        $rows = $pdo->query('SELECT * FROM contact_submissions ORDER BY id DESC')->fetchAll(\PDO::FETCH_ASSOC) ?: [];
        $html = $this->adminView('admin/contacts/index', ['rows' => $rows]);
        return Response::html($html);
    }

    public function show(Request $request): Response
    {
        $id = (int) ($request->param('id') ?? 0);
        $st = $this->app->pdo()->prepare('SELECT * FROM contact_submissions WHERE id = ?');
        $st->execute([$id]);
        $row = $st->fetch(\PDO::FETCH_ASSOC);
        if (! $row) {
            return $this->redirect(url('/admin/contacts'));
        }
        $html = $this->adminView('admin/contacts/show', ['row' => $row]);
        return Response::html($html);
    }

    public function status(Request $request): Response
    {
        if (! Csrf::verify($request->input('_csrf'))) {
            return $this->redirect(url('/admin/contacts'));
        }
        $id = (int) ($request->param('id') ?? 0);
        $status = $request->input('status', 'read');
        if (! in_array($status, ['new', 'read', 'archived'], true)) {
            $status = 'read';
        }
        $this->app->pdo()->prepare('UPDATE contact_submissions SET status = ? WHERE id = ?')->execute([$status, $id]);
        return $this->redirect(url('/admin/contacts/view/' . $id));
    }
}
