<?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 MENTORSHIP NETWORK\n";

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

$mentors=
$db->query("
SELECT
reviewer_id,
conference_id,
readiness_score,
succession_role
FROM reviewer_succession_plans
WHERE succession_role IN
(
'Conference Chair Successor',
'Track Chair Successor'
)
ORDER BY readiness_score DESC
")->fetchAll(PDO::FETCH_ASSOC);

$mentees=
$db->query("
SELECT
reviewer_id,
conference_id,
readiness_score
FROM reviewer_succession_plans
WHERE succession_role='Recovery Program'
ORDER BY readiness_score ASC
")->fetchAll(PDO::FETCH_ASSOC);

if(empty($mentors)){
    echo "NO MENTORS FOUND\n";
    exit;
}

$mentorCount=count($mentors);
$i=0;

foreach($mentees as $m){

    $mentor=
    $mentors[
        $i % $mentorCount
    ];

    $score=
    round(
        (
            $mentor['readiness_score']
            -
            $m['readiness_score']
        ),
        2
    );

    if($score < 0){
        $score=0;
    }

    $db->prepare("
    INSERT INTO reviewer_mentorship_network
    (
        mentor_reviewer_id,
        mentee_reviewer_id,
        conference_id,
        mentorship_type,
        mentorship_score,
        recommendation_text
    )
    VALUES
    (
        ?,?,?,?,?,?
    )
    ")->execute([
        $mentor['reviewer_id'],
        $m['reviewer_id'],
        $m['conference_id'],
        'Recovery Mentorship',
        $score,
        'Assign structured reviewer mentoring program'
    ]);

    $i++;
}

echo "DONE\n";
