<?php

define(
'BASE_PATH',
realpath(__DIR__.'/../..')
);

require_once BASE_PATH.'/config/autoload.php';
require_once BASE_PATH.'/config/bootstrap.php';

$db=\App\Core\Database::getInstance();

echo "REVIEW ESCALATIONS\n";

$db->exec(
"TRUNCATE TABLE review_escalations"
);

$rows=
$db->query("
SELECT *
FROM review_deadline_predictions
WHERE prediction_status='critical'
")->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $r){

    $replacement=
    $db->query("
        SELECT reviewer_id
        FROM reviewer_performance
        WHERE conference_id=".(int)$r['conference_id']."
        ORDER BY final_score DESC
        LIMIT 1
    ")->fetchColumn();

    $db->prepare("
    INSERT INTO review_escalations
    (
        conference_id,
        assignment_id,
        reviewer_id,
        escalation_type,
        escalation_reason,
        replacement_reviewer_id
    )
    VALUES
    (
        ?,?,?,?,?,?
    )
    ")->execute([
        $r['conference_id'],
        $r['assignment_id'],
        $r['reviewer_id'],
        'critical_deadline',
        'Predicted overdue review',
        $replacement
    ]);

}

echo "DONE\n";
