<?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 "REVIEWER RISK REBUILD\n";

$db->exec("
UPDATE reviewer_risk_flags
SET is_active=0
");

$rows=
$db->query("
SELECT *
FROM reviewer_performance
")->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $r){

    $reviewerId=
    (int)$r['reviewer_id'];

    $conferenceId=
    (int)$r['conference_id'];

    $completion=
    (float)$r['completion_rate'];

    $acceptance=
    (float)$r['acceptance_rate'];

    $quality=
    (float)$r['quality_score'];

    $finalScore=
    (float)$r['final_score'];

    $reviewCount=
    (int)$db->query("
        SELECT COUNT(*)
        FROM review_assignments
        WHERE reviewer_id=".$reviewerId."
        AND conference_id=".$conferenceId."
        AND status='completed'
    ")->fetchColumn();

    $assignedCount=
    (int)$db->query("
        SELECT COUNT(*)
        FROM review_assignments
        WHERE reviewer_id=".$reviewerId."
        AND conference_id=".$conferenceId."
    ")->fetchColumn();

    /*
    --------------------------------------
    PACK846C
    IGNORE LOW HISTORY REVIEWERS
    --------------------------------------
    */

    if(
        $reviewCount < 3
        &&
        $assignedCount < 5
    ){
        continue;
    }

    $riskScore=
    100
    -
    (
        ($completion*0.40)
        +
        ($acceptance*0.30)
        +
        ($quality*0.20)
        +
        ($finalScore*0.10)
    );

    $riskLevel='low';

    if($riskScore >= 70){
        $riskLevel='high';
    }
    elseif($riskScore >= 40){
        $riskLevel='medium';
    }

    if($riskScore < 40){
        continue;
    }

    $reason=
    'Calculated risk score '
    .round($riskScore,2);

    $db->prepare("
    INSERT INTO reviewer_risk_flags
    (
        conference_id,
        reviewer_id,
        risk_type,
        risk_score,
        risk_reason,
        review_count,
        assigned_count,
        risk_level,
        is_active
    )
    VALUES
    (
        ?,?,?,?,?,?,?,?,1
    )
    ")->execute([

        $conferenceId,
        $reviewerId,
        'performance_risk',
        $riskScore,
        $reason,
        $reviewCount,
        $assignedCount,
        $riskLevel

    ]);

}

echo "DONE\n";
