<?php

namespace App\Services;

use App\Core\Database;

class DoiService
{
    public static function generate(
        int $submissionId,
        int $conferenceId
    ): string
    {
        $db =
            Database::getInstance();

        /*
        Get prefix
        */

        $stmt =
            $db->prepare("
                SELECT doi_prefix
                FROM conference_doi_settings
                WHERE conference_id = ?
                LIMIT 1
            ");

        $stmt->execute([
            $conferenceId
        ]);

        $prefix =
            $stmt->fetchColumn();

        if (!$prefix) {

            $prefix =
                "10.0000/jpu";

        }

        /*
        Generate DOI
        */

        $doi =
            $prefix .
            "." .
            $submissionId;

        /*
        Ensure uniqueness
        */

        $stmt =
            $db->prepare("
                SELECT id
                FROM submissions
                WHERE doi = ?
                LIMIT 1
            ");

        $stmt->execute([
            $doi
        ]);

        if ($stmt->fetchColumn()) {

            $doi .=
                "." .
                time();

        }

        return $doi;
    }
}
