<?php

declare(strict_types=1);

class FrontContactController
{
    private const SUBJECT_TYPES = [
        'dmca_takedown',
        '2257_compliance',
        'content_report',
        'privacy_request',
        'technical_issue',
        'general_inquiry',
        'other',
    ];

    private const SUBJECT_LABELS = [
        'dmca_takedown'    => 'DMCA Takedown Request',
        '2257_compliance'  => '2257 Compliance',
        'content_report'   => 'Content Report',
        'privacy_request'  => 'Privacy Request',
        'technical_issue'  => 'Technical Issue',
        'general_inquiry'  => 'General Inquiry',
        'other'            => 'Other',
    ];

    private const URL_REQUIRED_SUBJECTS = ['dmca_takedown', '2257_compliance', 'content_report'];

    public static function routes(): void
    {
        Router::post('/contact-submit', [self::class, 'submit']);
    }

    public static function submit(): void
    {
         
        if (!Router::verifyCsrf()) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Session expired. Please try again.'];
            self::redirectBack();
            return;
        }

         
        if (!empty($_POST['website_url'])) {
            $_SESSION['flash'] = ['type' => 'success', 'message' => 'Thank you! Your message has been sent.'];
            self::redirectBack();
            return;
        }

         
        if (!RateLimiter::throttle('contact', 3, 10)) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Too many messages. Please try again later.'];
            self::redirectBack();
            return;
        }

         
        $name = Sanitizer::text(trim($_POST['contact_name'] ?? ''));
        $email = trim($_POST['contact_email'] ?? '');
        $subjectType = trim($_POST['contact_subject_type'] ?? '');
        $message = Sanitizer::text(trim($_POST['contact_message'] ?? ''));

        if ($name === '' || $email === '' || $subjectType === '' || $message === '') {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'All fields are required.'];
            self::redirectBack();
            return;
        }

        if (!in_array($subjectType, self::SUBJECT_TYPES, true)) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Please select a valid subject.'];
            self::redirectBack();
            return;
        }

        $subject = self::SUBJECT_LABELS[$subjectType] ?? 'Other';

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Please enter a valid email address.'];
            self::redirectBack();
            return;
        }

        if (mb_strlen($name) > 255 || mb_strlen($message) > 10000) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'One or more fields exceed the maximum length.'];
            self::redirectBack();
            return;
        }

         
        $contentUrls = [];
        $rawUrls = $_POST['content_urls'] ?? [];
        if (is_array($rawUrls)) {
            foreach ($rawUrls as $url) {
                $url = trim($url);
                if ($url !== '' && filter_var($url, FILTER_VALIDATE_URL)) {
                    $contentUrls[] = $url;
                }
            }
        }

         
        if (in_array($subjectType, self::URL_REQUIRED_SUBJECTS, true) && empty($contentUrls)) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Please provide at least one content URL.'];
            self::redirectBack();
            return;
        }

         
        if (!Captcha::verify('contact')) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'CAPTCHA verification failed. Please try again.'];
            self::redirectBack();
            return;
        }

         
        $pageId = null;
        $referer = $_SERVER['HTTP_REFERER'] ?? '';
        $path = parse_url($referer, PHP_URL_PATH);
        if ($path) {
            $slug = ltrim($path, '/');
            $page = Database::fetchOne('SELECT id FROM pages WHERE slug = ? AND has_contact_form = 1', [$slug]);
            if ($page) {
                $pageId = (int) $page['id'];
            }
        }

         
        $insertData = [
            'page_id' => $pageId,
            'name' => $name,
            'email' => $email,
            'subject' => $subject,
            'subject_type' => $subjectType,
            'message' => $message,
            'ip_address' => RateLimiter::ip(),
        ];
        if (!empty($contentUrls)) {
            $insertData['content_urls'] = json_encode($contentUrls, JSON_UNESCAPED_SLASHES);
        }
        ContactMessage::create($insertData);

         
        Telegram::notifyContact([
            'name' => $name, 'email' => $email, 'subject' => $subject,
            'subject_type' => $subjectType, 'message' => $message, 'ip' => RateLimiter::ip(),
        ]);

         
        $contactEmail = Setting::get('contact_email', '');
        if ($contactEmail !== '' && filter_var($contactEmail, FILTER_VALIDATE_EMAIL)) {
            $urlsHtml = '';
            if (!empty($contentUrls)) {
                $urlsHtml = '<div style="margin:12px 0;padding:12px;background:#fff3cd;border-radius:6px;border:1px solid #ffc107;font-size:13px;">'
                          . '<strong style="color:#856404;">Content URLs:</strong><ul style="margin:6px 0 0;padding-left:20px;">';
                foreach ($contentUrls as $url) {
                    $urlsHtml .= '<li><a href="' . htmlspecialchars($url) . '">' . htmlspecialchars($url) . '</a></li>';
                }
                $urlsHtml .= '</ul></div>';
            }
            try {
                Mailer::sendType('contact_forward', $contactEmail, [
                    '{site_name}'    => Setting::get('site_name', 'TubePress'),
                    '{name}'         => $name,
                    '{email}'        => $email,
                    '{subject}'      => $subject,
                    '{subject_type}' => $subjectType,
                    '{message}'      => $message,
                    '{ip}'           => RateLimiter::ip(),
                ], $email, ['{content_urls}' => $urlsHtml]);
            } catch (\Throwable $e) {
                 
            }
        }

        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Thank you! Your message has been sent successfully.'];
        self::redirectBack();
    }

    private static function redirectBack(): void
    {
        $referer = $_SERVER['HTTP_REFERER'] ?? '/';
        $path = parse_url($referer, PHP_URL_PATH);
        Router::redirect(($path && $path[0] === '/' && ($path[1] ?? '') !== '/' && ord($path[1] ?? '') !== 92) ? $path : '/');
    }
}
