<?php

namespace App\Services;

use App\Core\Database;

class RoleAssignmentService
{
    public static function assignRole(
        int $userId,
        int $conferenceId,
        string $roleCode,
        ?int $orgId,
        int $assignedBy
    ): void
    {
        $db = Database::getInstance();

        /*
        Prevent duplicate role
        */

        $stmt = $db->prepare("
            SELECT id
            FROM conference_user_roles
            WHERE user_id = ?
            AND conference_id = ?
            AND role_code = ?
            LIMIT 1
        ");

        $stmt->execute([
            $userId,
            $conferenceId,
            $roleCode
        ]);

        if ($stmt->fetchColumn()) {

            error_log(
                "ROLE EXISTS: "
                . $roleCode
                . " user="
                . $userId
            );

            return;
        }

        /*
        Insert role
        */

        $db->prepare("
            INSERT INTO conference_user_roles
            (
                user_id,
                conference_id,
                role_code,
                org_id,
                created_at
            )
            VALUES
            (?, ?, ?, ?, NOW())
        ")
        ->execute([
            $userId,
            $conferenceId,
            $roleCode,
            $orgId
        ]);

        /*
        Audit log
        */

        $db->prepare("
            INSERT INTO submission_status_history
            (
                submission_id,
                new_status,
                changed_by,
                created_at
            )
            VALUES
            (0, ?, ?, NOW())
        ")
        ->execute([
            "role_assigned_" . $roleCode,
            $assignedBy
        ]);

        error_log(
            "ROLE ASSIGNED: "
            . $roleCode
            . " user="
            . $userId
            . " conf="
            . $conferenceId
        );
    }
}
