<?php

namespace App\Controllers;

use App\Core\Database;
use PDO;

class AuthorSubmissionEntryController
{
    public function enter()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $db = Database::getInstance();

        $key = trim($_GET['id'] ?? '');

        if ($key === '') {
            die('Conference required');
        }

        $stmt = $db->prepare("
            SELECT id, org_id, slug, short_name
            FROM conferences
            WHERE slug = ?
               OR short_name = ?
               OR id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $key,
            $key,
            ctype_digit($key) ? (int)$key : 0
        ]);

        $conf = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$conf) {
            die('Conference not found');
        }

        $_SESSION['submit_conference_id'] = (int)$conf['id'];
        $_SESSION['conference_id'] = (int)$conf['id'];
        $_SESSION['org_id'] = (int)$conf['org_id'];
        $_SESSION['submit_slug'] = $conf['slug'] ?: $key;

        if (empty($_SESSION['user_id'])) {
            header(
                'Location: /easychair/register?conference_id=' .
                urlencode($conf['slug'] ?: $key)
            );
            exit;
        }

        header('Location: /easychair/author/submit?id=' . (int)$conf['id']);
        exit;
    }
}
