<?php
declare(strict_types=1);

namespace App\Controllers;

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

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

use App\Core\Controller;
use App\Models\DecisionModel;
use App\Models\Submission;
use App\Models\Review;
use App\Models\User;
use App\Services\NotificationService;
use App\Services\ConferenceNotificationService;

final class DecisionController extends Controller
{
    public function form(): void
    {
        require_permission('decisions.make');

        $submissionId = (int) ($_GET['submission_id'] ?? 0);
        if ($submissionId <= 0) {
            redirect('submissions');
        }

        $submissionModel = new Submission();
        $reviewModel = new Review();
        $decisionModel = new DecisionModel();

        $submission = $submissionModel->findById($submissionId);
        if (!$submission) {
            redirect('submissions');
        }

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

            $decision = trim((string) ($_POST['decision'] ?? ''));
            $chairComments = trim((string) ($_POST['chair_comments'] ?? ''));

            if (!in_array($decision, ['accept', 'minor_revision', 'major_revision', 'reject'], true)) {
                flash('danger', trans('required_fields'));
                redirect('decisions/form?submission_id=' . $submissionId);
            }

            $decisionModel->saveDecision([
                'submission_id' => $submissionId,
                'decided_by' => (int) auth_id(),
                'decision' => $decision,
                'chair_comments' => $chairComments,
            ]);

            $newStatus = match ($decision) {
                'accept' => 'accepted',
                'reject' => 'rejected',
                'minor_revision', 'major_revision' => 'revision_required',
                default => 'under_review',
            };

            $submissionModel->setStatus($submissionId, $newStatus, (int) auth_id());

            $author = (new User())->findById((int) $submission['author_id']);
            if ($author) {
                ConferenceNotificationService::notifyAndEmail(
                    $author,
                    (int) $submission['conference_id'],
                    'decision_made',
                    [
                        'user_name' => trim((string) $author['first_name'] . ' ' . (string) $author['last_name']),
                        'submission_no' => (string) $submission['submission_no'],
                        'submission_title' => (string) $submission['title'],
                        'conference_title' => current_lang() === 'ar' ? (string) $submission['title_ar'] : (string) $submission['title_en'],
                        'decision' => $decision,
                        'chair_comments' => $chairComments !== '' ? $chairComments : '-',
                    ],
                    'decision_made',
                    'submissions',
                    $submissionId
                );
            }

            audit_log('save_decision', 'decisions', $submissionId, [
                'decision' => $decision,
                'status' => $newStatus,
            ]);

            flash('success', trans('decision_saved_success'));
            redirect('submissions/show?id=' . $submissionId);
        }

        $this->view('decisions/form', [
            'submission' => $submission,
            'authors' => $submissionModel->authors($submissionId),
            'assignments' => $reviewModel->assignmentsForSubmission($submissionId),
            'currentDecision' => $decisionModel->getBySubmission($submissionId),
            'decisionHistory' => $decisionModel->historyBySubmission($submissionId),
            'reviewStats' => $decisionModel->aggregateReviewStats($submissionId),
        ]);
    }
}
