<?php

namespace App\Controllers;

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

use App\Core\Controller;
use App\Core\Database;

class SubmissionController extends Controller
{

    private function ensureSession()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }

    private function ensureConference()
    {
        $this->ensureSession();

        /*
         Must be logged in
        */

        if (!isset($_SESSION['user_id'])) {

            header("Location: /easychair/login");
            exit;

        }

        /*
         Read conference from URL
        */

        if (isset($_GET['id'])) {

            $_SESSION['conference_id'] = (int) $_GET['id'];

        }

        /*
         Fallback if still missing
        */

        if (!isset($_SESSION['conference_id'])) {

            $_SESSION['conference_id'] = 1;

        }

    }

    public function submit()
    {
        $this->ensureConference();

        require BASE_PATH . '/app/views/author/submit.php';

    }

    public function dashboard()
    {
        $this->ensureConference();

        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT *
            FROM submissions
            WHERE author_id = ?
            AND conference_id = ?
            ORDER BY id DESC
        ");

        $stmt->execute([
            $_SESSION['user_id'],
            $_SESSION['conference_id']
        ]);

        $submissions = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        require BASE_PATH . '/app/views/author/dashboard.php';

    }

public function nextStage()
{
     $this->requireLogin();

    requirePermission(
        'workflow.transition',
        'update'
    );

    $submissionId =
        (int)$_POST['submission_id'];

    try {

        \App\Services\WorkflowService::transitionSubmissionStage(

            $submissionId,

            $_SESSION['user_id']

        );

    }
    catch (\Exception $e) {

        die(
            $e->getMessage()
        );

    }

    header(
        "Location: /easychair/author/submission?id="
        . $submissionId
    );

}

}
