<?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 DEADLINE PREDICTIONS\n";

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

$rows=
$db->query("
SELECT
ra.id assignment_id,
ra.reviewer_id,
ra.conference_id,
COALESCE(rp.completion_rate,0) completion_rate,
COALESCE(rp.final_score,0) final_score,
COALESCE(rp.acceptance_rate,0) acceptance_rate,
DATEDIFF(
COALESCE(ra.due_date,CURDATE()),
CURDATE()
) days_remaining
FROM review_assignments ra
LEFT JOIN reviewer_performance rp
ON rp.reviewer_id=ra.reviewer_id
AND rp.conference_id=ra.conference_id
WHERE ra.status IN
(
'assigned',
'accepted'
)
")->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $r){

    $score=0;

    $score +=
    (100-(float)$r['completion_rate'])
    *0.30;

    $score +=
    (100-(float)$r['acceptance_rate'])
    *0.20;

    if(
        (int)$r['days_remaining'] <= 7
    ){
        $score += 30;
    }

    if(
        (int)$r['days_remaining'] <= 3
    ){
        $score += 20;
    }

    $status='safe';

    if($score >= 70){
        $status='critical';
    }
    elseif($score >= 40){
        $status='at_risk';
    }

    $db->prepare("
    INSERT INTO review_deadline_predictions
    (
        conference_id,
        assignment_id,
        reviewer_id,
        prediction_status,
        prediction_score,
        days_remaining
    )
    VALUES
    (
        ?,?,?,?,?,?
    )
    ")->execute([
        $r['conference_id'],
        $r['assignment_id'],
        $r['reviewer_id'],
        $status,
        $score,
        $r['days_remaining']
    ]);

}

echo "DONE\n";
