<?php

namespace App\Services;

use App\Core\Database;

class ReviewerLoadService
{
    public static function getReviewerLoad(
        int $reviewerId,
        int $conferenceId
    ): int
    {
        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE reviewer_id = ?
            AND conference_id = ?
            AND status IN
            (
                'assigned',
                'accepted'
            )
        ");

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

        return (int)$stmt->fetchColumn();
    }

    public static function getMaxLoad(
        int $conferenceId
    ): int
    {
        $db = Database::getInstance();

        try{

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

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

            $v=(int)$stmt->fetchColumn();

            return $v > 0
                ? $v
                : 5;

        }catch(\Throwable $e){

            return 5;

        }
    }

    public static function getCapacityPercent(
        int $reviewerId,
        int $conferenceId
    ): int
    {
        $load =
        self::getReviewerLoad(
            $reviewerId,
            $conferenceId
        );

        $max =
        self::getMaxLoad(
            $conferenceId
        );

        if($max <= 0){
            return 0;
        }

        return (int)round(
            ($load / $max) * 100
        );
    }

    public static function canAssign(
        int $reviewerId,
        int $conferenceId,
        ?int $maxLoad = null
    ): bool
    {
        if($maxLoad === null){

            $maxLoad =
            self::getMaxLoad(
                $conferenceId
            );
        }

        $load =
        self::getReviewerLoad(
            $reviewerId,
            $conferenceId
        );

        return $load < $maxLoad;
    }

    public static function alreadyAssigned(
        int $submissionId,
        int $reviewerId
    ): bool
    {
        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT id
            FROM review_assignments
            WHERE submission_id = ?
            AND reviewer_id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $submissionId,
            $reviewerId
        ]);

        return (bool)$stmt->fetchColumn();
    }
}
