<?php

declare(strict_types=1);

class AdminContactMessageController
{
    public static function routes(): void
    {
        Router::get('/admin/messages', [self::class, 'index']);
        Router::get('/admin/messages/{id}', [self::class, 'show']);
        Router::get('/admin/messages/{id}/json', [self::class, 'showJson']);
        Router::post('/admin/messages/{id}/read', [self::class, 'toggleRead']);
        Router::post('/admin/messages/{id}/delete', [self::class, 'destroy']);
    }

    public static function index(): void
    {
        Router::redirect('/admin/inbox?tab=messages');
    }

    public static function show(): void
    {
        Auth::requireAdmin();
        $id = (int) Router::param('id');
        $message = ContactMessage::find($id);
        if (!$message) {
            Router::redirect('/admin/messages');
            return;
        }

        if (!$message['is_read']) {
            ContactMessage::markRead($id);
            $message['is_read'] = 1;
        }

        Router::render('admin/message_view', [
            'pageTitle' => 'View Message',
            'activeMenu' => 'inbox',
            'contentTemplate' => '_message_view',
            'message' => $message,
        ]);
    }

    

    public static function showJson(): void
    {
        Auth::requireAdmin();
        $id = (int) Router::param('id');
        $msg = ContactMessage::find($id);
        if (!$msg) {
            Router::json(['error' => 'Message not found'], 404);
            return;
        }

        $wasUnread = !$msg['is_read'];
        if ($wasUnread) {
            ContactMessage::markRead($id);
            $msg['is_read'] = 1;
        }

        $contentUrls = [];
        if (!empty($msg['content_urls'])) {
            $contentUrls = json_decode($msg['content_urls'], true) ?: [];
        }

        Router::json([
            'id'              => (int) $msg['id'],
            'name'            => $msg['name'],
            'email'           => $msg['email'],
            'subject'         => $msg['subject'],
            'subject_type'    => $msg['subject_type'] ?? '',
            'message'         => $msg['message'],
            'ip_address'      => $msg['ip_address'] ?? '',
            'is_read'         => (int) $msg['is_read'],
            'was_unread'      => $wasUnread,
            'content_urls'    => $contentUrls,
            'created_at'      => $msg['created_at'],
            'created_at_long' => date('F j, Y \a\t g:i A', strtotime($msg['created_at'])),
            'created_at_rel'  => self::relativeTime($msg['created_at']),
        ]);
    }

    

    public static function toggleRead(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) {
            Router::json(['error' => 'Invalid CSRF token'], 403);
            return;
        }
        $id = (int) Router::param('id');
        $msg = ContactMessage::find($id);
        if (!$msg) {
            Router::json(['error' => 'Message not found'], 404);
            return;
        }

        $state = isset($_POST['state']) ? (int) $_POST['state'] : 1;
        if ($state === 1) {
            ContactMessage::markRead($id);
        } else {
            Database::update('contact_messages', ['is_read' => 0], 'id = ?', [$id]);
        }

        Router::json(['success' => true, 'is_read' => $state]);
    }

    public static function destroy(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) {
            if (self::wantsJson()) {
                Router::json(['error' => 'Invalid CSRF token'], 403);
                return;
            }
            Router::redirect('/admin/messages');
        }
        ContactMessage::delete((int) Router::param('id'));

        if (self::wantsJson()) {
            Router::json(['success' => true]);
            return;
        }
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Message deleted.'];
        Router::redirect('/admin/messages');
    }

    private static function wantsJson(): bool
    {
        return !empty($_POST['_ajax'])
            || (isset($_SERVER['HTTP_ACCEPT']) && str_contains($_SERVER['HTTP_ACCEPT'], 'application/json'))
            || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest');
    }

    private static function relativeTime(string $datetime): string
    {
        $diff = time() - strtotime($datetime);
        if ($diff < 60) return $diff . 's ago';
        if ($diff < 3600) return floor($diff / 60) . 'm ago';
        if ($diff < 86400) return floor($diff / 3600) . 'h ago';
        if ($diff < 604800) return floor($diff / 86400) . 'd ago';
        return date('M j', strtotime($datetime));
    }
}
