<?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 . "user_management/authenticate.php";
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning_resources . "includes/specific_db_config.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . "user_management/functions/functions.php";
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

checkIfNoPhpContentsReceive();

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

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['teacher'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

function get_student_marksheet_data($conn_rjllearning_specific, $institution_id, $branch_id, $student_id, $class_id, $section_id, $marksheet_id, $academic_id, $limit, $offset)
{
    $sql_count = "SELECT count(*) as total_rows FROM student_marksheet_data where institution_id =? AND academic_id = ? AND branch_id = ?";
    $array_params = [$institution_id, $academic_id, $branch_id];

    if ($student_id == 'all') {
        $sql_count .= "";
    } else if ($student_id !=  null  && $student_id != 'all') {
        $sql_count .= " AND student_id = ? ";
        $array_params[] = $student_id;
    }

    if ($class_id == 'all') {
        $sql_count .= "";
    } else if ($class_id !=  null  && $class_id != 'all') {
        $sql_count .= " AND class_id = ? ";
        $array_params[] = $class_id;
    }

    if ($section_id == 'all') {
        $sql_count .= "";
    } else if ($section_id !=  null  and $section_id != 'all') {
        $sql_count .= " AND section_id LIKE ? ";
        $array_params[] = '%' . $section_id . '%';
    }
    
    if ($marksheet_id == null) {
        $sql_count .= "";
    } else if ($marksheet_id !=  null  && $marksheet_id != 'all') {
        $sql_count .= " AND marksheet_id = ? ";
        $array_params[] = $marksheet_id;
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    // For specific student, return normal response
    if ($student_id != 'all') {
        if ($limit == 'all') {
            $sql_session = "SELECT * FROM student_marksheet_data where institution_id =? AND academic_id = ? AND branch_id = ?";
            $array_params = [$institution_id, $academic_id, $branch_id];

            if ($student_id == 'all') {
                $sql_session .= "";
            } else if ($student_id !=  null  && $student_id != 'all') {
                $sql_session .= " AND student_id = ? ";
                $array_params[] = $student_id;
            }

            if ($class_id == 'all') {
                $sql_session .= "";
            } else if ($class_id !=  null  && $class_id != 'all') {
                $sql_session .= " AND class_id = ? ";
                $array_params[] = $class_id;
            }

            if ($section_id == 'all') {
                $sql_session .= "";
            } else if ($section_id !=  null  and $section_id != 'all') {
                $sql_session .= " AND section_id LIKE ? ";
                $array_params[] = '%' . $section_id . '%';
            }
            
            if ($marksheet_id == null) {
                $sql_session .= "";
            } else if ($marksheet_id !=  null  && $marksheet_id != 'all') {
                $sql_session .= " AND marksheet_id = ? ";
                $array_params[] = $marksheet_id;
            }

            $sql_session .=  "order by date_created desc, time_created desc";
        } else {
            $sql_session = "SELECT * FROM student_marksheet_data where institution_id =? AND academic_id = ? AND branch_id = ?";
            $array_params = [$institution_id, $academic_id, $branch_id];

            if ($student_id == 'all') {
                $sql_session .= "";
            } else if ($student_id !=  null  && $student_id != 'all') {
                $sql_session .= " AND student_id = ? ";
                $array_params[] = $student_id;
            }

            if ($class_id == 'all') {
                $sql_session .= "";
            } else if ($class_id !=  null  && $class_id != 'all') {
                $sql_session .= " AND class_id = ? ";
                $array_params[] = $class_id;
            }

            if ($section_id == 'all') {
                $sql_session .= "";
            } else if ($section_id !=  null  and $section_id != 'all') {
                $sql_session .= " AND section_id LIKE ? ";
                $array_params[] = '%' . $section_id . '%';
            }
            
            if ($marksheet_id == null) {
                $sql_session .= "";
            } else if ($marksheet_id !=  null  && $marksheet_id != 'all') {
                $sql_session .= " AND marksheet_id = ? ";
                $array_params[] = $marksheet_id;
            }

            $sql_session .= " order by date_created desc, time_created desc ";
            $sql_session .= "LIMIT " . $offset . " ," . $limit . "";
        }
        
        $stmt = $conn_rjllearning_specific->prepare($sql_session);
        $stmt->execute($array_params);
        $session_rows = $stmt->fetchAll();

        $array_return = [];

        foreach ($session_rows as $rows) {
            $data = json_decode($rows['data'], true);
            $analytics = [];
            if (isset($rows['analytics']) && $rows['analytics'] !== null) {
                $analytics = json_decode($rows['analytics'], true);
            }

            $section_info = getSection($conn_rjllearning_specific, $institution_id, $rows['section_id']);
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows['class_id']);
            $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);

            $student_info = [];
            $res = $conn_rjllearning_specific->prepare("SELECT id, name FROM students WHERE id = ? AND institution_id = ?");
            $res->execute([$rows['student_id'], $institution_id]);
            $result = $res->fetch(PDO::FETCH_ASSOC);

            if ($result) {
                $student_info = [
                    "student_id" => $result['id'],
                    "student_name" => $result['name']
                ];
            }

            $array_return[] = [
                'id' => $rows['id'],
                'branch_info' => $branch_info,
                'student_info' => $student_info,
                'class_info' => $class_info,
                'section_info' => $section_info,
                'analytics' => $analytics,
                'marksheet_id' => $rows['marksheet_id'],
                'created_by' => $rows['created_by'],
                'date_created' => $rows['date_created'],
                'time_created' => $rows['time_created'],
                'status' => $rows['status']
            ];
        }

        if (count($session_rows) < 50) {
            return array('total_rows' => $totalrows, 'marksheet_data_info' => $array_return, 'maxreach' => 1);
        } else {
            return array('total_rows' => $totalrows, 'marksheet_data_info' => $array_return, 'maxreach' => 0);
        }
    }
    // For all students, return only aggregate analytics
    else {
        // Get all student marksheets for the class/section
        $sql_all = "SELECT smd.*, s.name as student_name 
                   FROM student_marksheet_data smd
                   JOIN students s ON smd.student_id = s.id
                   WHERE smd.institution_id = ? AND smd.academic_id = ? AND smd.branch_id = ?";
        
        $params = [$institution_id, $academic_id, $branch_id];
        
        if ($class_id != 'all') {
            $sql_all .= " AND smd.class_id = ?";
            $params[] = $class_id;
        }
        if ($section_id != 'all') {
            $sql_all .= " AND smd.section_id LIKE ?";
            $params[] = '%' . $section_id . '%';
        }
        
        if ($marksheet_id != null) {
            $sql_all .= " AND smd.marksheet_id = ?";
            $params[] = $marksheet_id;
        }
        
        $sql_all .= " ORDER BY smd.date_created DESC, smd.time_created DESC";
        
        $stmt = $conn_rjllearning_specific->prepare($sql_all);
        $stmt->execute($params);
        $all_marksheets = $stmt->fetchAll();

        // Process all marksheets to calculate aggregate analytics
        $subject_stats = [];
        $total_percentage = 0;
        $student_percentages = [];
        $count = 0;

        foreach ($all_marksheets as $marksheet) {
            if (!empty($marksheet['analytics'])) {
                $analytics = json_decode($marksheet['analytics'], true);
                $total_percentage += $analytics['percentage'];
                $count++;
                
                // Collect subject percentages
                foreach ($analytics['subject_rankings'] as $subject_ranking) {
                    $subject = $subject_ranking['subject'];
                    if (!isset($subject_stats[$subject])) {
                        $subject_stats[$subject] = [];
                    }
                    $subject_stats[$subject][] = $subject_ranking['percentage'];
                }
                
                // Prepare student data for top/bottom lists
                $section_info = getSection($conn_rjllearning_specific, $institution_id, $marksheet['section_id']);
                $class_info = getClass($conn_rjllearning_specific, $institution_id, $marksheet['class_id']);
                $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $marksheet['branch_id']);
                
                $student_data = [
                    'id' => $marksheet['id'],
                    'branch_info' => $branch_info, 
                    'student_info' => [
                        'student_id' => $marksheet['student_id'],
                        'student_name' => $marksheet['student_name']
                    ],
                    'class_info' => $class_info,
                    'section_info' => $section_info,
                    'analytics' => $analytics,
                    'marksheet_id' => $marksheet['marksheet_id'],
                    'created_by' => $marksheet['created_by'],
                    'date_created' => $marksheet['date_created'],
                    'time_created' => $marksheet['time_created'],
                    'status' => $marksheet['status']
                ];
                
                $student_percentages[] = [
                    'percentage' => $analytics['percentage'],
                    'data' => $student_data
                ];
            }
        }
        
        // Calculate average percentage
        $average_percentage = $count > 0 ? round($total_percentage / $count, 2) : 0;
        
        // Calculate subject averages
        $subject_averages = [];
        foreach ($subject_stats as $subject => $percentages) {
            $subject_averages[$subject] = round(array_sum($percentages) / count($percentages), 2);
        }
        
        // Determine highest and lowest scoring subjects
        $highest_subject = null;
        $lowest_subject = null;
        
        if (!empty($subject_averages)) {
            arsort($subject_averages);
            $highest_subject = [
                'subject' => array_key_first($subject_averages),
                'average_percentage' => $subject_averages[array_key_first($subject_averages)]
            ];
            
            asort($subject_averages);
            $lowest_subject = [
                'subject' => array_key_first($subject_averages),
                'average_percentage' => $subject_averages[array_key_first($subject_averages)]
            ];
        }
        
        // Sort students by percentage
        usort($student_percentages, function($a, $b) {
            return $b['percentage'] <=> $a['percentage'];
        });
        
        // Get top 5 and bottom 5 students
        $top_five = array_slice($student_percentages, 0, 5);
        $bottom_five = array_slice($student_percentages, -5, 5);
        $bottom_five = array_reverse($bottom_five);
        
        // Prepare final response
        $response = [
            'total_rows' => $totalrows,
            'highest_score_subject' => $highest_subject,
            'lowest_score_subject' => $lowest_subject,
            'average_percentage_of_all_student' => $average_percentage,
            'top_five_student' => array_column($top_five, 'data'),
            'bottom_five_student' => array_column($bottom_five, 'data')
        ];
        
        return $response;
    }
}

if ($postdata['function_type'] == "fetch_marksheets_analytics") {
    
    $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    $class_section_subjects  = $teacher_data['class_section_subjects'];
    $class_incharge_roles = $teacher_data['class_incharge_roles'];
    $staff_access_modules = $teacher_data['staff_access_modules'];

    $check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, null, null, null, $conn_rjllearning);
    if ($check_faculty_status == false) {
        errorreturn("Access denied: You do not have the required permissions.");
    }
    
    if (isset($postdata['student_id']) and !empty($postdata['student_id'])) {
        $student_id = trim($postdata['student_id']);
    } else {
        $student_id = 'all';
    }
    if (isset($postdata['class_id']) and !empty($postdata['class_id'])) {
        $class_id = trim($postdata['class_id']);
    } else {
        $class_id = 'all';
    }
    if (isset($postdata['section_id']) and !empty($postdata['section_id'])) {
        $section_id = trim($postdata['section_id']);
    } else {
        $section_id = 'all';
    }
    
    if (isset($postdata['marksheet_id']) and !empty($postdata['marksheet_id'])) {
        $marksheet_id = trim($postdata['marksheet_id']);
    } else {
        $marksheet_id = null;
    }
    
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    // print_r($check_academic_confirmation);
    // die();
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }
    
    
    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;
    
    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = get_student_marksheet_data($conn_rjllearning_specific, $institution_id, $branch_id, $student_id, $class_id, $section_id, $marksheet_id, 
        $check_academic_confirmation, $limit, $offset);
        successreturn($success);
    } else {
        $success['data'] = get_student_marksheet_data($conn_rjllearning_specific, $institution_id, $branch_id, $student_id, $class_id, $section_id, $marksheet_id, 
        $check_academic_confirmation, $limit, null);
        successreturn($success);
    }
}
