<?php

namespace App\Controllers;

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

use App\Core\Controller;
use App\Core\Database;
use App\Services\Certification\CertificationEngine;
use PDO;
use Throwable;

class AdminWorkflowCertificationController extends Controller
{
    public function index(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (!isset($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

        $conferenceId = (int)(
            $_GET['conference_id']
            ??
            $_SESSION['conference_id']
            ??
            0
        );

        $engine = new CertificationEngine();

        $report =
            $engine->run(
                $conferenceId > 0
                    ? $conferenceId
                    : null
            );

        $this->render(
            'admin/workflow_certification/index',
            [

                'report'
                    =>
                    $report,

                'summary'
                    =>
                    $report['summary'],

                'results'
                    =>
                    $report['results'],

                'conferenceId'
                    =>
                    $conferenceId,

                'conferences'
                    =>
                    $this->conferences(),

                'pageTitle'
                    =>
                    function_exists('trans')
                        ? trans(
                            'menu.workflow_certification_center'
                        )
                        : 'Workflow Certification Center',

                'activeMenu'
                    =>
                    'workflow_certification_center'

            ]
        );
    }

    private function conferences(): array
    {
        try {

            $db =
                Database::getInstance();

            $stmt =
                $db->query(
                    "
                    SELECT

                        id,

                        title,

                        acronym

                    FROM conferences

                    ORDER BY id DESC
                    "
                );

            return
                $stmt->fetchAll(PDO::FETCH_ASSOC)
                ?: [];

        } catch (Throwable $e) {

            error_log(
                'WORKFLOW CERTIFICATION: '
                .
                $e->getMessage()
            );

            return [];

        }
    }
}
