<?php

namespace App\Services;

use App\Core\Database;

class ReviewRoundService
{
    public static function startNextRound(
        int $submissionId,
        int $userId
    ): void
    {
        $db =
            Database::getInstance();

        /*
        Get submission
        */

        $stmt =
            $db->prepare("
                SELECT
                    current_round_no,
                    conference_id,
                    org_id
                FROM submissions
                WHERE id = ?
                LIMIT 1
            ");

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

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

        if (!$submission) {
            return;
        }

        $nextRound =
            (int)$submission['current_round_no'] + 1;

        /*
        Update round number
        */

        $db->prepare("
            UPDATE submissions
            SET
                current_round_no = ?,
                stage = 'review',
                status = 'under_review',
                updated_by = ?,
                updated_at = NOW()
            WHERE id = ?
        ")
        ->execute([
            $nextRound,
            $userId,
            $submissionId
        ]);

        /*
        Copy reviewers from previous round
        */

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

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

        $reviewers =
            $stmt->fetchAll(
                \PDO::FETCH_COLUMN
            );

        /*
        Reset assignments
        */

        foreach ($reviewers as $reviewerId) {

            $db->prepare("
                INSERT INTO review_assignments
                (
                    submission_id,
                    reviewer_id,
                    conference_id,
                    org_id,
                    status,
                    created_at
                )
                VALUES
                (?, ?, ?, ?, 'assigned', NOW())
            ")
            ->execute([

                $submissionId,
                $reviewerId,
                $submission['conference_id'],
                $submission['org_id']

            ]);

        }

        /*
        Log history
        */

        $db->prepare("
            INSERT INTO submission_status_history
            (
                submission_id,
                new_status,
                changed_by,
                created_at
            )
            VALUES
            (?, 'new_review_round', ?, NOW())
        ")
        ->execute([
            $submissionId,
            $userId
        ]);

        error_log(
            "NEW REVIEW ROUND: submission="
            . $submissionId .
            " round="
            . $nextRound
        );
    }
}
