<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/conference_scope.php';

use App\Core\Controller;
use App\Models\Conference;
use App\Models\ProceedingsBookModel;
use App\Models\ReviewerAnalyticsModel;
use App\Models\Submission;
use App\Models\SubmissionCheckModel;

final class PublishingExtrasController extends Controller
{
    public function bookIndex(): void
    {
        require_permission('proceedings_book.view');

        $conferenceId = (int)
\request_conference_id();
        if ($conferenceId <= 0) {
            $confs = (new Conference())->all();
            if (!empty($confs)) {
                redirect('admin/proceedings-book/edit?conference_id=' . (int) $confs[0]['id']);
            }
            redirect('admin');
        }

        redirect('admin/proceedings-book/edit?conference_id=' . $conferenceId);
    }

    public function bookEdit(): void
    {
        require_permission('proceedings_book.manage');

        $conferenceId = (int) ($_GET['conference_id'] ?? ($_POST['conference_id'] ?? 0));
        if ($conferenceId <= 0) {
            redirect('admin');
        }

        $conference = (new Conference())->findById($conferenceId);
        if (!$conference) {
            redirect('admin');
        }

        $model = new ProceedingsBookModel();

        if ($this->isPost()) {
            csrf_check();

            $data = [
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'isbn_print' => trim((string) ($_POST['isbn_print'] ?? '')),
                'isbn_online' => trim((string) ($_POST['isbn_online'] ?? '')),
                'editor_en' => trim((string) ($_POST['editor_en'] ?? '')),
                'editor_ar' => trim((string) ($_POST['editor_ar'] ?? '')),
                'preface_en' => trim((string) ($_POST['preface_en'] ?? '')),
                'preface_ar' => trim((string) ($_POST['preface_ar'] ?? '')),
                'cover_image' => trim((string) ($_POST['cover_image'] ?? '')),
                'is_published' => isset($_POST['is_published']) ? 1 : 0,
            ];

            if ($data['title_en'] === '') {
                flash('danger', trans('required_fields'));
                redirect('admin/proceedings-book/edit?conference_id=' . $conferenceId);
            }

            $model->save($conferenceId, $data);
            audit_log('save_proceedings_book', 'proceedings_books', $conferenceId, $data);
            flash('success', trans('save'));
            redirect('admin/proceedings-book/edit?conference_id=' . $conferenceId);
        }

        $this->view('admin/proceedings_book/edit', [
            'conference' => $conference,
            'conferences' => (new Conference())->all(),
            'row' => $model->getByConference($conferenceId),
        ]);
    }

    public function reviewerAnalytics(): void
    {
        require_permission('reviewer_analytics.view');

        $this->view('admin/reviewer_analytics/index', [
            'rows' => (new ReviewerAnalyticsModel())->summary(),
        ]);
    }

    public function checksIndex(): void
    {
        require_permission('submission_checks.view');

        $this->view('admin/submission_checks/index', [
            'rows' => (new SubmissionCheckModel())->all(),
            'submissions' => (new Submission())->all(),
        ]);
    }

    public function checksEdit(): void
    {
        require_permission('submission_checks.manage');

        $submissionId = (int) ($_GET['submission_id'] ?? ($_POST['submission_id'] ?? 0));
        if ($submissionId <= 0) {
            redirect('admin/submission-checks');
        }

        $submission = (new Submission())->findById($submissionId);
        if (!$submission) {
            redirect('admin/submission-checks');
        }

        $model = new SubmissionCheckModel();

        if ($this->isPost()) {
            csrf_check();

            $data = [
                'plagiarism_score' => trim((string) ($_POST['plagiarism_score'] ?? '')),
                'plagiarism_notes' => trim((string) ($_POST['plagiarism_notes'] ?? '')),
                'format_check_status' => trim((string) ($_POST['format_check_status'] ?? 'pending')),
                'format_notes' => trim((string) ($_POST['format_notes'] ?? '')),
                'checklist_json' => json_encode([
                    'title_ok' => isset($_POST['check_title']) ? 1 : 0,
                    'abstract_ok' => isset($_POST['check_abstract']) ? 1 : 0,
                    'keywords_ok' => isset($_POST['check_keywords']) ? 1 : 0,
                    'format_ok' => isset($_POST['check_format']) ? 1 : 0,
                    'references_ok' => isset($_POST['check_references']) ? 1 : 0,
                ], JSON_UNESCAPED_UNICODE),
                'checked_by' => auth_id(),
            ];

            $model->save($submissionId, $data);
            audit_log('save_submission_checks', 'submission_checks', $submissionId, $data);
            flash('success', trans('save'));
            redirect('admin/submission-checks');
        }

        $this->view('admin/submission_checks/edit', [
            'submission' => $submission,
            'row' => $model->findBySubmission($submissionId),
        ]);
    }
}
