<?php

declare(strict_types=1);

class FrontReportController
{
    public static function routes(): void
    {
        Router::post('/video/{id}/report', [self::class, 'store']);
        Router::post('/album/{id}/report', [self::class, 'storeAlbum']);
    }

    public static function store(): void
    {
        if (!Router::verifyCsrf()) {
            Router::json(['error' => 'csrf_failed', 'message' => 'Your session has expired. Please refresh the page.'], 403);
        }

        $videoId = (int) Router::param('id');
        $ip = RateLimiter::ip();

         
        $video = Database::fetchOne('SELECT id FROM videos WHERE id = ?', [$videoId]);
        if (!$video) {
            Router::json(['error' => 'not_found', 'message' => 'Video not found.'], 404);
        }

        $input = json_decode(file_get_contents('php://input'), true);

         
        if (isset($input['_sg_ts'])) $_POST['_sg_ts'] = $input['_sg_ts'];
        if (isset($input['_sg_h']))  $_POST['_sg_h']  = $input['_sg_h'];
        if (isset($input['website'])) $_POST['website'] = $input['website'];

        $reason  = $input['reason'] ?? '';
        $details = trim($input['details'] ?? '');

        if (!in_array($reason, Report::REASONS, true)) {
            Router::json(['error' => 'invalid_reason', 'message' => 'Please select a valid reason.'], 400);
        }

         
        $spamError = SpamGuard::validate($details ?: $reason, $ip, $videoId, 'report');
        if ($spamError !== null) {
            $messages = [
                'spam_detected'           => 'Spam detected.',
                'comment_too_fast'        => 'You are submitting too fast. Please wait a moment.',
                'comment_rate_limited'    => 'Too many reports. Please try again later.',
                'comment_duplicate'       => 'You have already reported this video.',
                'comment_too_short'       => 'Please provide a bit more detail.',
                'comment_too_long'        => 'Your report is too long. Please shorten it.',
                'comment_too_many_links'  => 'Please remove links from your report.',
            ];
            $msg = $messages[$spamError] ?? 'Your report could not be submitted.';
            $code = $spamError === 'comment_rate_limited' ? 429 : ($spamError === 'comment_duplicate' ? 409 : 400);
            Router::json(['error' => $spamError, 'message' => $msg], $code);
        }

         
        $reporterEmail = trim($input['reporter_email'] ?? '');
        if ($reporterEmail !== '' && !filter_var($reporterEmail, FILTER_VALIDATE_EMAIL)) {
            $reporterEmail = '';
        }

        Report::create([
            'video_id'       => $videoId,
            'user_id'        => Auth::check() ? Auth::id() : null,
            'reason'         => $reason,
            'details'        => $details !== '' ? Sanitizer::text(mb_substr($details, 0, 1000)) : null,
            'reporter_email' => $reporterEmail !== '' ? $reporterEmail : null,
            'ip_address'     => $ip,
        ]);

         
        $vid = Database::fetchOne('SELECT title, slug FROM videos WHERE id = ?', [$videoId]);
        $videoTitle = $vid['title'] ?? ('#' . $videoId);
        $videoUrl = rtrim((string) Setting::get('site_url', ''), '/') . '/video/' . ($vid['slug'] ?? (string) $videoId);
        Telegram::notifyReport([
            'video_title'    => $videoTitle,
            'video_url'      => $videoUrl,
            'reason'         => $reason,
            'details'        => $details,
            'reporter_email' => $reporterEmail,
            'ip'             => $ip,
        ]);
        $contactEmail = Setting::get('contact_email', '');
        if ($contactEmail !== '' && filter_var($contactEmail, FILTER_VALIDATE_EMAIL)) {
            try {
                Mailer::sendType('report_notification', $contactEmail, [
                    '{site_name}'      => Setting::get('site_name', 'TubePress'),
                    '{video_title}'    => $videoTitle,
                    '{video_url}'      => $videoUrl,
                    '{reason}'         => $reason,
                    '{details}'        => $details,
                    '{reporter_email}' => $reporterEmail !== '' ? $reporterEmail : '—',
                    '{ip}'             => (string) $ip,
                ]);
            } catch (\Throwable $e) {
                 
            }
        }

        Router::json(['success' => true, 'message' => 'Thank you. Your report has been submitted.']);
    }

     
    public static function storeAlbum(): void
    {
        if (!Router::verifyCsrf()) {
            Router::json(['error' => 'csrf_failed', 'message' => 'Your session has expired. Please refresh the page.'], 403);
        }

        $albumId = (int) Router::param('id');
        $ip = RateLimiter::ip();

        $album = Database::fetchOne('SELECT id FROM albums WHERE id = ?', [$albumId]);
        if (!$album) {
            Router::json(['error' => 'not_found', 'message' => 'Gallery not found.'], 404);
        }

        $input = json_decode(file_get_contents('php://input'), true);
        if (isset($input['_sg_ts'])) $_POST['_sg_ts'] = $input['_sg_ts'];
        if (isset($input['_sg_h']))  $_POST['_sg_h']  = $input['_sg_h'];
        if (isset($input['website'])) $_POST['website'] = $input['website'];

        $reason  = $input['reason'] ?? '';
        $details = trim($input['details'] ?? '');

        if (!in_array($reason, Report::REASONS, true)) {
            Router::json(['error' => 'invalid_reason', 'message' => 'Please select a valid reason.'], 400);
        }

        $spamError = SpamGuard::validate($details ?: $reason, $ip, $albumId, 'album_report');
        if ($spamError !== null) {
            $messages = [
                'spam_detected'           => 'Spam detected.',
                'comment_too_fast'        => 'You are submitting too fast. Please wait a moment.',
                'comment_rate_limited'    => 'Too many reports. Please try again later.',
                'comment_duplicate'       => 'You have already reported this gallery.',
                'comment_too_short'       => 'Please provide a bit more detail.',
                'comment_too_long'        => 'Your report is too long. Please shorten it.',
                'comment_too_many_links'  => 'Please remove links from your report.',
            ];
            $msg = $messages[$spamError] ?? 'Your report could not be submitted.';
            $code = $spamError === 'comment_rate_limited' ? 429 : ($spamError === 'comment_duplicate' ? 409 : 400);
            Router::json(['error' => $spamError, 'message' => $msg], $code);
        }

        $reporterEmail = trim($input['reporter_email'] ?? '');
        if ($reporterEmail !== '' && !filter_var($reporterEmail, FILTER_VALIDATE_EMAIL)) {
            $reporterEmail = '';
        }

        Report::create([
            'album_id'       => $albumId,
            'user_id'        => Auth::check() ? Auth::id() : null,
            'reason'         => $reason,
            'details'        => $details !== '' ? Sanitizer::text(mb_substr($details, 0, 1000)) : null,
            'reporter_email' => $reporterEmail !== '' ? $reporterEmail : null,
            'ip_address'     => $ip,
        ]);

        $alb = Database::fetchOne('SELECT title, slug FROM albums WHERE id = ?', [$albumId]);
        $albumTitle = ($alb['title'] ?? ('#' . $albumId)) . ' (gallery)';
        $albumUrl = rtrim((string) Setting::get('site_url', ''), '/') . '/album/' . ($alb['slug'] ?? (string) $albumId);
        Telegram::notifyReport([
            'video_title'    => $albumTitle,
            'video_url'      => $albumUrl,
            'reason'         => $reason,
            'details'        => $details,
            'reporter_email' => $reporterEmail,
            'ip'             => $ip,
        ]);
        $contactEmail = Setting::get('contact_email', '');
        if ($contactEmail !== '' && filter_var($contactEmail, FILTER_VALIDATE_EMAIL)) {
            try {
                Mailer::sendType('report_notification', $contactEmail, [
                    '{site_name}'      => Setting::get('site_name', 'TubePress'),
                    '{video_title}'    => $albumTitle,
                    '{video_url}'      => $albumUrl,
                    '{reason}'         => $reason,
                    '{details}'        => $details,
                    '{reporter_email}' => $reporterEmail !== '' ? $reporterEmail : '—',
                    '{ip}'             => (string) $ip,
                ]);
            } catch (\Throwable $e) {
                 
            }
        }

        Router::json(['success' => true, 'message' => 'Thank you. Your report has been submitted.']);
    }
}
