<?php

declare(strict_types=1);

class AdminReportController
{
    public static function routes(): void
    {
        Router::get('/admin/reports', [self::class, 'index']);
        Router::get('/admin/reports/{id}', [self::class, 'show']);
        Router::get('/admin/reports/{id}/json', [self::class, 'showJson']);
        Router::post('/admin/reports/{id}/status', [self::class, 'updateStatus']);
        Router::post('/admin/reports/{id}/delete', [self::class, 'destroy']);
        Router::post('/admin/reports/{id}/delete-video', [self::class, 'deleteVideo']);
        Router::post('/admin/reports/{id}/delete-album', [self::class, 'deleteAlbum']);
    }

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

    public static function show(): void
    {
        Auth::requireAdmin();

        $id = (int) Router::param('id');
        $report = Report::find($id);
        if (!$report) {
            Router::redirect('/admin/reports');
        }

        Router::render('admin/report_view', [
            'pageTitle'       => 'Report #' . $id,
            'activeMenu'      => 'inbox',
            'contentTemplate' => '_report_view',
            'report'          => $report,
            'reportCount'     => Report::countForSubject($report),
        ]);
    }

    public static function showJson(): void
    {
        Auth::requireAdmin();

        $id = (int) Router::param('id');
        $report = Report::find($id);
        if (!$report) {
            Router::json(['error' => 'not_found'], 404);
            return;
        }

        $subject = Report::subject($report);
        Router::json([
            'id'               => (int) $report['id'],
            'subject_type'     => $subject['type'],
            'subject_id'       => $subject['id'],
            'subject_label'    => $subject['label'],
            'subject_title'    => $subject['title'],
            'subject_view_url' => $subject['view_url'],
            'subject_edit_url' => $subject['edit_url'],
             
            'video_id'         => (int) ($report['video_id'] ?? 0),
            'video_title'      => $subject['title'],
            'video_slug'       => $report['video_slug'] ?? '',
            'username'         => $report['username'] ?? 'Guest',
            'reporter_email'   => $report['reporter_email'] ?? null,
            'reason'           => $report['reason'],
            'reason_label'     => Report::REASON_LABELS[$report['reason']] ?? $report['reason'],
            'status'           => $report['status'],
            'status_label'     => Report::STATUS_LABELS[$report['status']] ?? $report['status'],
            'details'          => $report['details'],
            'admin_note'       => $report['admin_note'] ?? '',
            'ip_address'       => $report['ip_address'] ?? '',
            'created_at'       => $report['created_at'],
            'report_count'     => Report::countForSubject($report),
        ]);
    }

    public static function updateStatus(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) {
            if (!empty($_POST['_ajax'])) {
                Router::json(['success' => false, 'error' => 'Session expired.'], 403);
                return;
            }
            Router::redirect('/admin/reports');
        }

        $id = (int) Router::param('id');
        $status = $_POST['status'] ?? '';
        $adminNote = trim($_POST['admin_note'] ?? '');

        if (!in_array($status, ['pending', 'reviewed', 'resolved', 'dismissed'], true)) {
            if (!empty($_POST['_ajax'])) {
                Router::json(['success' => false, 'error' => 'Invalid status.'], 400);
                return;
            }
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'Invalid status.'];
            Router::redirect('/admin/reports/' . $id);
        }

        Report::updateStatus($id, $status, $adminNote !== '' ? $adminNote : null);

        if (!empty($_POST['_ajax'])) {
            Router::json([
                'success'      => true,
                'status'       => $status,
                'status_label' => Report::STATUS_LABELS[$status] ?? $status,
            ]);
            return;
        }

        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Report status updated.'];
        Router::redirect('/admin/reports/' . $id);
    }

    public static function deleteVideo(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) {
            Router::json(['success' => false, 'error' => 'Session expired.'], 403);
            return;
        }

        $id = (int) Router::param('id');
        $report = Report::find($id);
        if (!$report) {
            Router::json(['success' => false, 'error' => 'Report not found.'], 404);
            return;
        }

        $videoId = (int) $report['video_id'];

         
        Video::delete($videoId);

         
        Database::query(
            "UPDATE reports SET status = 'resolved', admin_note = CONCAT(COALESCE(admin_note, ''), '\n[Video deleted by admin]'), updated_at = NOW() WHERE video_id = ?",
            [$videoId]
        );

        Router::json(['success' => true, 'message' => 'Video deleted and all reports resolved.']);
    }

    public static function deleteAlbum(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) {
            Router::json(['success' => false, 'error' => 'Session expired.'], 403);
            return;
        }

        $id = (int) Router::param('id');
        $report = Report::find($id);
        if (!$report || empty($report['album_id'])) {
            Router::json(['success' => false, 'error' => 'Report not found.'], 404);
            return;
        }

        $albumId = (int) $report['album_id'];
        Album::delete($albumId);
        Database::query(
            "UPDATE reports SET status = 'resolved', admin_note = CONCAT(COALESCE(admin_note, ''), '\n[Gallery deleted by admin]'), updated_at = NOW() WHERE album_id = ?",
            [$albumId]
        );

        Router::json(['success' => true, 'message' => 'Gallery deleted and all reports resolved.']);
    }

    public static function destroy(): void
    {
        Auth::requireAdmin();
        $ajax = !empty($_POST['_ajax']);
        if (!Router::verifyCsrf()) {
            if ($ajax) {
                Router::json(['success' => false, 'error' => 'Session expired. Please reload the page.'], 403);
            }
            Router::redirect('/admin/reports');
        }

        Report::delete((int) Router::param('id'));

        if ($ajax) {
            Router::json(['success' => true]);
        }

        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Report deleted.'];
        Router::redirect('/admin/inbox?tab=reports');
    }
}
