<?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 "AUTHOR RESEARCH IMPACT REBUILD\n";

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

$sql="
SELECT
author_id,
conference_id,

COUNT(*) submission_count,

SUM(
CASE
WHEN status='accepted'
THEN 1 ELSE 0
END
) accepted_count,

SUM(
CASE
WHEN status='published'
THEN 1 ELSE 0
END
) published_count

FROM submissions

WHERE author_id IS NOT NULL

GROUP BY
author_id,
conference_id
";

$rows=
$db->query($sql)
->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $r){

    $submissions=
    (int)$r['submission_count'];

    $accepted=
    (int)$r['accepted_count'];

    $published=
    (int)$r['published_count'];

    $impact=
    round(
        min(
            100,
            ($accepted*15)
            +
            ($published*25)
            +
            ($submissions*5)
        ),
        2
    );

    $level='Developing';

    if($impact>=80){
        $level='High Impact';
    }elseif($impact>=60){
        $level='Strong Impact';
    }elseif($impact>=40){
        $level='Growing Impact';
    }

    $maturity='Emerging';

    if($published>=5){
        $maturity='Established';
    }elseif($published>=2){
        $maturity='Advancing';
    }

    $recommendation=
    'Continue increasing publication quality and conference engagement.';

    $db->prepare("
        INSERT INTO
        author_research_impact
        (
            author_id,
            conference_id,
            submission_count,
            accepted_count,
            published_count,
            impact_score,
            influence_level,
            research_maturity,
            recommendation_text
        )
        VALUES
        (?,?,?,?,?,?,?,?,?)
    ")->execute([
        $r['author_id'],
        $r['conference_id'],
        $submissions,
        $accepted,
        $published,
        $impact,
        $level,
        $maturity,
        $recommendation
    ]);
}

echo "DONE\n";
