<?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\ConferenceWorkflowModel;
use App\Models\ReviewCriteriaModel;
use App\Models\ConferenceEmailTemplateModel;

final class WorkflowController extends Controller
{
    public function index(): void
    {
        require_permission('workflow.view');

        $conferences = (new Conference())->all();

        $this->view('admin/workflow/index', [
            'conferences' => $conferences,
            'rules' => (new ConferenceWorkflowModel())->all(),
        ]);
    }

    public function editConferenceRules(): void
    {
        require_permission('workflow.manage');

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

        $confModel = new Conference();
        $ruleModel = new ConferenceWorkflowModel();

        $conference = $confModel->findById($conferenceId);
        if (!$conference) {
            redirect('admin/workflow');
        }

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

            $data = [
                'min_reviewers' => (int) ($_POST['min_reviewers'] ?? 2),
                'blind_review_mode' => trim((string) ($_POST['blind_review_mode'] ?? 'double')),
                'allow_author_edit_before_deadline' => isset($_POST['allow_author_edit_before_deadline']) ? 1 : 0,
                'allow_revision_round' => isset($_POST['allow_revision_round']) ? 1 : 0,
                'require_camera_ready' => isset($_POST['require_camera_ready']) ? 1 : 0,
                'auto_ack_email' => isset($_POST['auto_ack_email']) ? 1 : 0,
                'auto_reviewer_assignment_email' => isset($_POST['auto_reviewer_assignment_email']) ? 1 : 0,
                'auto_decision_email' => isset($_POST['auto_decision_email']) ? 1 : 0,
                'auto_revision_email' => isset($_POST['auto_revision_email']) ? 1 : 0,
                'auto_camera_ready_email' => isset($_POST['auto_camera_ready_email']) ? 1 : 0,
            ];

            $ruleModel->save($conferenceId, $data);
            audit_log('save_workflow_rules', 'conference_workflow_rules', $conferenceId, $data);
            flash('success', trans('workflow_saved_success'));
            redirect('admin/workflow');
        }

        $this->view('admin/workflow/edit', [
            'conference' => $conference,
            'rule' => $ruleModel->getByConference($conferenceId),
        ]);
    }

    public function criteriaIndex(): void
    {
        require_permission('review_criteria.view');

        $conferenceId = (int)
\request_conference_id();
        $conference = $conferenceId > 0 ? (new Conference())->findById($conferenceId) : null;

        $this->view('admin/review_criteria/index', [
            'conferences' => (new Conference())->all(),
            'conference' => $conference,
            'rows' => $conferenceId > 0 ? (new ReviewCriteriaModel())->byConference($conferenceId) : [],
        ]);
    }

    public function criteriaCreate(): void
    {
        require_permission('review_criteria.manage');

        $confModel = new Conference();

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

            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'criterion_key' => trim((string) ($_POST['criterion_key'] ?? '')),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'description_en' => trim((string) ($_POST['description_en'] ?? '')),
                'description_ar' => trim((string) ($_POST['description_ar'] ?? '')),
                'min_score' => (float) ($_POST['min_score'] ?? 1),
                'max_score' => (float) ($_POST['max_score'] ?? 5),
                'weight' => (float) ($_POST['weight'] ?? 1),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];

            if ($data['conference_id'] <= 0 || $data['criterion_key'] === '' || $data['title_en'] === '' || $data['title_ar'] === '') {
                flash('danger', trans('required_fields'));
                redirect('admin/review-criteria/create');
            }

            $id = (new ReviewCriteriaModel())->create($data);
            audit_log('create_review_criterion', 'review_criteria', $id, $data);
            flash('success', trans('criterion_saved_success'));
            redirect('admin/review-criteria?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/review_criteria/create', [
            'conferences' => $confModel->all(),
        ]);
    }

    public function criteriaEdit(): void
    {
        require_permission('review_criteria.manage');

        $id = (int) ($_GET['id'] ?? 0);
        $model = new ReviewCriteriaModel();
        $row = $model->findById($id);

        if (!$row) {
            redirect('admin/review-criteria');
        }

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

            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'criterion_key' => trim((string) ($_POST['criterion_key'] ?? '')),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'description_en' => trim((string) ($_POST['description_en'] ?? '')),
                'description_ar' => trim((string) ($_POST['description_ar'] ?? '')),
                'min_score' => (float) ($_POST['min_score'] ?? 1),
                'max_score' => (float) ($_POST['max_score'] ?? 5),
                'weight' => (float) ($_POST['weight'] ?? 1),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];

            $model->update($id, $data);
            audit_log('update_review_criterion', 'review_criteria', $id, $data);
            flash('success', trans('criterion_saved_success'));
            redirect('admin/review-criteria?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/review_criteria/edit', [
            'row' => $row,
            'conferences' => (new Conference())->all(),
        ]);
    }

    public function templateIndex(): void
    {
        require_permission('conference_email_templates.view');

        $conferenceId = (int)
\request_conference_id();
        $conference = $conferenceId > 0 ? (new Conference())->findById($conferenceId) : null;

        $this->view('admin/conference_templates/index', [
            'conferences' => (new Conference())->all(),
            'conference' => $conference,
            'rows' => $conferenceId > 0 ? (new ConferenceEmailTemplateModel())->byConference($conferenceId) : [],
        ]);
    }

    public function templateCreate(): void
    {
        require_permission('conference_email_templates.manage');

        $conferences = (new Conference())->all();

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

            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'event_key' => trim((string) ($_POST['event_key'] ?? '')),
                'subject_en' => trim((string) ($_POST['subject_en'] ?? '')),
                'subject_ar' => trim((string) ($_POST['subject_ar'] ?? '')),
                'body_en' => trim((string) ($_POST['body_en'] ?? '')),
                'body_ar' => trim((string) ($_POST['body_ar'] ?? '')),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];

            if ($data['conference_id'] <= 0 || $data['event_key'] === '' || $data['subject_en'] === '' || $data['subject_ar'] === '') {
                flash('danger', trans('required_fields'));
                redirect('admin/conference-templates/create');
            }

            $id = (new ConferenceEmailTemplateModel())->create($data);
            audit_log('create_conference_email_template', 'conference_email_templates', $id, $data);
            flash('success', trans('conference_template_saved_success'));
            redirect('admin/conference-templates?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/conference_templates/create', [
            'conferences' => $conferences,
        ]);
    }

    public function templateEdit(): void
    {
        require_permission('conference_email_templates.manage');

        $id = (int) ($_GET['id'] ?? 0);
        $model = new ConferenceEmailTemplateModel();
        $row = $model->findById($id);

        if (!$row) {
            redirect('admin/conference-templates');
        }

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

            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'event_key' => trim((string) ($_POST['event_key'] ?? '')),
                'subject_en' => trim((string) ($_POST['subject_en'] ?? '')),
                'subject_ar' => trim((string) ($_POST['subject_ar'] ?? '')),
                'body_en' => trim((string) ($_POST['body_en'] ?? '')),
                'body_ar' => trim((string) ($_POST['body_ar'] ?? '')),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];

            $model->update($id, $data);
            audit_log('update_conference_email_template', 'conference_email_templates', $id, $data);
            flash('success', trans('conference_template_saved_success'));
            redirect('admin/conference-templates?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/conference_templates/edit', [
            'row' => $row,
            'conferences' => (new Conference())->all(),
        ]);
    }
}
