<?php
ini_set('display_errors', 1);

require_once '../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

// Validation file
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';
// DB access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
//aws image store
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';

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

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

if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['assignment_id']) or !checkIfIssetAndNotEmpty($postdata['assignment_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  !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is in decoded data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

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

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

function getSpecificAssignment($conn_rjllearning_specific, $assignment_id, $institution_id, $branch_id)
{
    $sql = "SELECT * FROM assignments WHERE id = ? AND institution_id = ? AND branch_id = ?";
    $array_params = [$assignment_id, $institution_id, $branch_id];

    $sql .= " ORDER BY date_created ASC, time_created ASC";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result = $stmt->fetchAll();
    $assignment_questions = array();

    if (count($result) == 1) {
        $sql = "SELECT * FROM assignment_questions WHERE assignment_id = ? AND institution_id = ? AND branch_id = ? ";
        $array_params = [$result[0]['id'], $institution_id, $branch_id];
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute($array_params);
        $result_question = $stmt->fetchAll();
        if (count($result_question) >= 1) {
            // $section_id = $result[0]['section_id'];
            // $section_info = [];
            // if ($section_id == 'all') {
            //     $section_info = array('section_id' => $section_id, 'section_name' => ucwords($section_id));
            // } else {
            //     $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($section_id)";
            //     $array_params = [$institution_id];
            //     $stmt = $conn_rjllearning_specific->prepare($sql);
            //     $stmt->execute($array_params);
            //     $section_rows = $stmt->fetchAll();

            //     foreach ($section_rows as $section_data) {
            //         $section_info = array('section_id' => $section_data['id'], 'section_name' => $section_data['section_name']);
            //     }
            // }
            $section_info = getSection($conn_rjllearning_specific, $institution_id, $result[0]['section_id']);
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $result[0]['class_id']);
            $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $result[0]['subject_id']);
            $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $result[0]['branch_id']);

            foreach ($result_question as $temp) {
                if ($temp['question_attachment'] != null && !is_array($temp['question_attachment'])) {
                    $data_attachment = json_decode($temp['question_attachment'], true);
                    $filePath = $data_attachment['filepath'];
                    $originalName = $data_attachment['original_name'];
                    $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                    $final_question_attachment = ["filepath" => $aws_attachment, "original_name" => $originalName];
                } else {
                    $final_question_attachment =  null;
                }
                $options = !empty($temp['options']) ? json_decode($temp['options'], true) : null;

                $sql_avg = "SELECT AVG(marks_obtained) as average_marks 
                            FROM assignment_submission 
                            WHERE assignment_questions_id = ? 
                            AND institution_id = ? AND branch_id = ? AND status = 1";
                $stmt_avg = $conn_rjllearning_specific->prepare($sql_avg);
                $stmt_avg->execute([$temp['id'], $institution_id, $branch_id]);
                $avg_row = $stmt_avg->fetch(PDO::FETCH_ASSOC);

                if ($avg_row['average_marks'] !== null) {
                    $average_marks = $avg_row['average_marks'];

                    // Check if the number is a float (has decimals)
                    if (fmod($average_marks, 1) != 0) {
                        $average_marks = number_format($average_marks, 1); // Format to 1 decimal place
                    } else {
                        $average_marks = (int) $average_marks; // Keep it as an integer
                    }
                }else{
                    $average_marks =null;
                }

                $sql_highest = "SELECT MAX(marks_obtained) as highest_marks 
                        FROM assignment_submission 
                        WHERE assignment_questions_id = ? 
                        AND institution_id = ? AND branch_id = ? AND status = 1";
                $stmt_highest = $conn_rjllearning_specific->prepare($sql_highest);
                $stmt_highest->execute([$temp['id'], $institution_id, $branch_id]);
                $high_row = $stmt_highest->fetch(PDO::FETCH_ASSOC);
                // $highest_marks = (int) ($high_row['highest_marks'] ?? 0);
                $highest_marks = isset($high_row['highest_marks']) ? (int) $high_row['highest_marks'] : 0;

                // 3. Lowest marks for the question
                $sql_lowest = "SELECT MIN(marks_obtained) as lowest_marks 
                                FROM assignment_submission 
                                WHERE assignment_questions_id = ? 
                                AND institution_id = ? AND branch_id = ? AND status = 1";
                $stmt_lowest = $conn_rjllearning_specific->prepare($sql_lowest);
                $stmt_lowest->execute([$temp['id'], $institution_id, $branch_id]);
                $low_row = $stmt_lowest->fetch(PDO::FETCH_ASSOC);
                // $lowest_marks = (int) ($low_row['lowest_marks'] ?? 0);
                $lowest_marks = isset($low_row['lowest_marks']) ? (int) $low_row['lowest_marks'] : 0;


                // 4. Mode (Most Frequent Mark)
                $sql_mode = "SELECT marks_obtained FROM assignment_submission WHERE assignment_questions_id = ? AND institution_id = ? 
                             AND branch_id  = ? AND status = 1 GROUP BY marks_obtained HAVING COUNT(*) > 1 
                            ORDER BY COUNT(*) DESC, marks_obtained DESC 
                            LIMIT 1";
                $stmt_mode = $conn_rjllearning_specific->prepare($sql_mode);
                $stmt_mode->execute([$temp['id'], $institution_id, $branch_id]);
                $mode_row = $stmt_mode->fetch(PDO::FETCH_ASSOC);
                $mode = $mode_row ? (int) $mode_row['marks_obtained'] : null;

                $assignment_questions[] = array(
                    "assignment_questions_id" => $temp['id'],
                    "institution_id" => $temp['institution_id'],
                    "branch_id" => $temp['branch_id'],
                    "question_no" => $temp['question_no'],
                    "question_type" => $temp['question_type'],
                    'question_text' => $temp['question_text'],
                    "options" => $options,
                    "answer" => $temp['answer'],
                    "question_attachment" => $final_question_attachment,
                    "question_marks" => $temp['question_marks'],
                    "average_marks" => $average_marks,
                    "highest_marks" => $highest_marks,
                    "lowest_marks" => $lowest_marks,
                    "mode" => $mode
                );
            }

            $array_return = array(
                "assignment_id" => $result[0]['id'],
                'branch_id' => $branch,
                'class_info' => $class_info,
                'section_id' => $section_info,
                'subject_info' => $subject_info,
                "name" => $result[0]['name'],
                "description" => $result[0]['description'],
                "max_points" => $result[0]['max_points'],
                "publish_date" => $result[0]['publish_date'],
                "last_date" => $result[0]['last_date'],
                "can_submit_after_last_date" => $result[0]['can_submit_after_last_date'],
                "publish_time" => $result[0]['publish_time'],
                "last_submission_time" => $result[0]['last_submission_time'],
                "assignment_questions" => $assignment_questions
            );
        }

        return $array_return;
    }
}

if ($postdata['function_type'] == "fetch_specific_assignment") {
    
    $assignment_id = trim($postdata['assignment_id']);


    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    $success['data'] = getSpecificAssignment($conn_rjllearning_specific, $assignment_id, $institution_id, $branch_id);
    successreturn($success);
}
