<?php

ini_set('display_errors', 1);

require_once '../../resources/base_path_include.php';
require_once $base_path_to_learning_resources . "includes/connect.php";
require_once $base_path_to_learning_resources . "lib/function.php";
require_once $base_path_to_learning_resources . "lib/validate_api_signature.php";

require_once $base_path_to_learning_resources.'lib/validate_function.php';
require_once $base_path_to_learning.'admin_api/branch_management/functions/functions.php';
require_once $base_path_to_learning.'user_management/authenticate.php';
require_once $base_path_to_learning.'functions/common_functions.php';
require_once $base_path_to_learning_resources.'includes/specific_db_config.php';

try {

    $postdata = json_decode(file_get_contents("php://input"), true);
    checkIfNoPhpContentsReceive();

    if (!isset($postdata['api_signature']) ||
        !isset($postdata['function_type']) ||
        !isset($postdata['jwt_token'])
    ) {
        errorreturn("All * fields are required.");
    }

    validateApiSignature($postdata['api_signature']);

    // JWT
    $jwt = authenticate_jwt($postdata['jwt_token']);
    $userid  = $jwt->data->id;
    $role    = $jwt->data->role;
    $workspace_id = $jwt->data->workspace_id;
    $institution_id_jwt = $jwt->data->institution_id;

    // DB
    $specific_db_name = validateUserAccess(
        $conn_rjllearning,
        $userid,
        $role,
        $workspace_id,
        ["superadmin","admin","teacher"],
        null
    );

    if (!$specific_db_name) errorreturn("Access denied.");

    $db = dynamicDbConnection($specific_db_name);

    if ($postdata['function_type'] !== "fetch_analysis_report") {
        errorreturn("Invalid function_type.");
    }

    // FILTERS
    $institution_id = $postdata['institution_id'] ?? $institution_id_jwt;
    $branch_id      = $postdata['branch_id'] ?? null;
    $class_id       = $postdata['class_id'] ?? null;
    $section_id     = $postdata['section_id'] ?? null;
    $academic_id    = $postdata['academic_id'] ?? null;
    $marksheet_id   = $postdata['marksheet_id'] ?? null;

    // WHERE
    $where = ["institution_id = ?"];
    $params = [$institution_id];

    if ($branch_id) { $where[] = "branch_id = ?"; $params[] = $branch_id; }
    if ($academic_id) { $where[] = "academic_id = ?"; $params[] = $academic_id; }
    if ($class_id && strtolower($class_id) !== "all") { $where[] = "class_id = ?"; $params[] = $class_id; }
    if ($section_id && strtolower($section_id) !== "all") { $where[] = "section_id = ?"; $params[] = $section_id; }
    if ($marksheet_id) { $where[] = "marksheet_id = ?"; $params[] = $marksheet_id; }

    $WHERE = implode(" AND ", $where);

    // FETCH ROWS
    $stmt = $db->prepare("SELECT * FROM student_marksheet_data WHERE $WHERE");
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // SUBJECT MAP
    $subjectMap = [
        "English"      => [1,2,3,4],
        "Mathematics"  => [7,8,9],
        "Punjabi"      => [12,13],
        "EVS / GK"     => [16,17,18],
        "Rhymes"       => [],
        "Story"        => [],
        "Conversation" => [27]
    ];

    // grade list
    $gradeKeys = ['A1','A2','B1','B2','C1','C2','D','E'];

    // analysis init
    $analysis = [];
    foreach ($subjectMap as $sub => $idx) {
        $analysis[$sub] = [
            "total_students" => 0,
            "PASS" => 0,
            "FAIL" => 0
        ];
        foreach ($gradeKeys as $g) $analysis[$sub][$g] = 0;
    }

    // track unique student per subject
    $track = [];

    function normalizeGrade($g) {
        if ($g === null || $g === "") return null;
        $x = strtoupper(str_replace(" ", "", $g));

        // A → A1 rule
        if ($x === "A") return "A1";
        if ($x === "B") return "B1";
        if ($x === "C") return "C1";
        if ($x === "D") return "D";
        if ($x === "E") return "E";

        return $x;
    }

    function cleanSubject($s) {
        $s = strtolower($s);
        if (str_contains($s,'english')) return "English";
        if (str_contains($s,'math')) return "Mathematics";
        if (str_contains($s,'punj')) return "Punjabi";
        if (str_contains($s,'evs') || str_contains($s,'gk')) return "EVS / GK";
        if (str_contains($s,'rhyme')) return "Rhymes";
        if (str_contains($s,'story')) return "Story";
        if (str_contains($s,'conversation')) return "Conversation";
        return $s;
    }

    // MAIN LOOP
    foreach ($rows as $r) {

        $sid = $r['student_id'];

        $data = json_decode($r['data'], true);
        if (!is_array($data)) $data = [];

        $analytics = json_decode($r['analytics'], true);
        if (!is_array($analytics)) $analytics = [];

        // ------------------------
        // 1. ANALYTICS GRADES FIRST
        // ------------------------
        if (isset($analytics['subject_rankings'])) {

            foreach ($analytics['subject_rankings'] as $sr) {

                $subject = cleanSubject($sr['subject']);
                $grade   = normalizeGrade($sr['grade']);

                if (!isset($analysis[$subject])) continue;
                if ($grade === null) continue;

                if (!isset($track[$subject])) $track[$subject] = [];

                // UNIQUE student per subject
                if (!in_array($sid, $track[$subject])) {
                    $track[$subject][] = $sid;
                    $analysis[$subject]["total_students"]++;

                    if ($grade === "E") $analysis[$subject]["FAIL"]++;
                    else $analysis[$subject]["PASS"]++;
                }

                // grade count
                if (in_array($grade,$gradeKeys)) {
                    $analysis[$subject][$grade]++;
                }
            }
        }

        // ------------------------
        // 2. DATA COLUMN (if analytics missing)
        // ------------------------
        foreach ($subjectMap as $subject => $indexes) {

            if (!isset($track[$subject])) $track[$subject] = [];

            // skip if already counted from analytics
            if (in_array($sid,$track[$subject])) continue;

            $grades = [];

            foreach ($indexes as $i) {
                if (!empty($data[$i])) {
                    $g = normalizeGrade($data[$i]);
                    if ($g) $grades[] = $g;
                }
            }

            if (count($grades) === 0) continue;

            // pick best grade
            $priority = ['A1','A2','B1','B2','C1','C2','D','E'];
            usort($grades,function($a,$b)use($priority){
                return array_search($a,$priority) <=> array_search($b,$priority);
            });

            $final = $grades[0];

            // count student
            $track[$subject][] = $sid;
            $analysis[$subject]["total_students"]++;

            if ($final === "E") $analysis[$subject]["FAIL"]++;
            else $analysis[$subject]["PASS"]++;

            $analysis[$subject][$final]++;
        }
    }

    // response
    successreturn([
        "status" => true,
        "analysis_report" => $analysis
    ]);

} catch (Exception $e) {
    errorreturn("Error: " . $e->getMessage());
}
?>
