<?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['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_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);
}

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_type = trim($postdata['function_type']);

function fetchTemplates_details($institution_id, $conn_rjllearning_specific, $search_string, $userid, $branch_id, $conn_rjllearning, $function_type, $limit, $offset)
{
    try {
        $Faculty_Codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
        $Faculty_Codes->execute(array($userid, $institution_id, $branch_id));

        // Fetch a single row instead of all
        $result_faculty = $Faculty_Codes->fetch(PDO::FETCH_ASSOC);

        // Check if the faculty exists
        if ($result_faculty === false) {
            errorreturn("Faculty Not Found.");
        }

        // Retrieve the faculty_id from the result
        $faculty_id = $result_faculty['id'];
        
 $sql_count = "SELECT COUNT(*) AS total_rows 
                      FROM marksheet m 
                      WHERE m.institution_id = ?";
        $array_params = [$institution_id];

        if ($search_string != null) {
            $sql_count .= " AND (m.academic_session LIKE ? 
                              OR m.examination_name LIKE ? 
                              OR m.marksheet_name LIKE ?)";
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
        }

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


        if ($limit == 'all') {
            
            $sql_marksheet_info = "SELECT mi.marksheet_id, mi.branch_id, mi.class_id FROM marksheet_info mi INNER JOIN marksheet m ON 
            mi.marksheet_id = m.id WHERE mi.institution_id = ? AND mi.branch_id = ?";
            $array_params = [$institution_id, $branch_id];

            if ($search_string != null) {
                $sql_marksheet_info .= " AND (m.academic_session LIKE ? OR m.examination_name LIKE ?)";
                $array_params[] = '%' . $search_string . '%';
                $array_params[] = '%' . $search_string . '%';
            }
        } else {
            $sql_marksheet_info = "SELECT mi.marksheet_id, mi.branch_id, mi.class_id FROM marksheet_info mi INNER JOIN marksheet m ON 
            mi.marksheet_id = m.id WHERE mi.institution_id = ? AND mi.branch_id = ?";
            $array_params = [$institution_id, $branch_id];

            if ($search_string != null) {
                $sql_marksheet_info .= " AND (m.academic_session LIKE ? OR m.examination_name LIKE ?)";
                $array_params[] = '%' . $search_string . '%';
                $array_params[] = '%' . $search_string . '%';
            }

            $sql_marksheet_info .= "LIMIT " . $offset . " ," . $limit . "";
        }

        $stmt_marksheet_info = $conn_rjllearning_specific->prepare($sql_marksheet_info);
        $stmt_marksheet_info->execute($array_params);
        $marksheet_info_data = $stmt_marksheet_info->fetchAll();

        if (!$marksheet_info_data) {
            errorreturn('No marksheets found for this institution.');
        }

        $marksheets = [];
        $processed_marksheets = [];

        foreach ($marksheet_info_data as $row_info) {
            $marksheet_id = $row_info['marksheet_id'];

            // If this marksheet_id has been processed, skip it
            if (isset($processed_marksheets[$marksheet_id])) {
                continue;
            }

            // Now, fetch data from the marksheet table for each marksheet_id
            $sql_marksheet = "SELECT academic_session, examination_name, date_created, added_by FROM marksheet WHERE id = ? AND institution_id = ?";
            $stmt_marksheet = $conn_rjllearning_specific->prepare($sql_marksheet);
            $stmt_marksheet->execute([$marksheet_id, $institution_id]);
            $marksheet_data = $stmt_marksheet->fetch();

            // If no marksheet data is found, skip this marksheet_id
            if (!$marksheet_data) {
                continue;
            }
            // Group rows by marksheet_id
            $filtered_rows = array_filter($marksheet_info_data, function ($r) use ($marksheet_id) {
                return $r['marksheet_id'] == $marksheet_id;
            });

            // Collect unique branch_ids, class_ids, and section_ids
            $branch_ids = array_unique(array_column($filtered_rows, 'branch_id'));
            $class_ids = array_unique(array_column($filtered_rows, 'class_id'));
            // $section_ids = array_unique(array_column($filtered_rows, 'section_id'));

            // Determine branch info
            if (count($branch_ids) === 1  and $row_info['branch_id'] != 'all') {
                $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_ids[0]);
            } else {
                $branch_info = 'Multiple';
            }

            // Determine class info
            if (count($class_ids) === 1 and $row_info['class_id'] != 'all') {
                $class_info = getClass($conn_rjllearning_specific, $institution_id, $class_ids[0]);
            } else {
                $class_info = 'Multiple';
            }

            // Determine section info
            // if (count($section_ids) === 1  and $row_info['section_id'] !='all') {
            //     $section_info = getSection($conn_rjllearning_specific, $institution_id, $section_ids[0]);
            // } else {
            //     $section_info = 'Multiple';
            // }

            // Add the consolidated marksheet information
            $marksheets[] = [
                'marksheet_id' => $marksheet_id,
                'examination' => $marksheet_data['examination_name'],
                // 'marksheet_name' => $marksheet_data['marksheet_name'],
                'academic_session' => $marksheet_data['academic_session'],
                'branch' => $branch_info,
                'class' => $class_info,
                // 'section' => $section_info,
                'created_on' => $marksheet_data['date_created'],
                'created_by' => $marksheet_data['added_by']
            ];

            // Mark this marksheet_id as processed
            $processed_marksheets[$marksheet_id] = true;
        }
        if (count($marksheet_info_data) < 50) {
            return array('total_rows' => $totalrows, 'marksheet_info' => $marksheets, 'maxreach' => 1);
        } else {
            return array('total_rows' => $totalrows, 'marksheet_info' => $marksheets, 'maxreach' => 0);
        }
    } catch (Exception $e) {
        errorreturn("Error: " . $e->getMessage());
        return;
    }
}

if ($postdata['function_type'] == "fetch_marksheets") {
    $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['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = fetchTemplates_details($institution_id, $conn_rjllearning_specific, $search_string, $userid, $branch_id, $conn_rjllearning, $function_type, $limit, $offset);
        successreturn($success);
    } else {
        $success['data'] = fetchTemplates_details($institution_id, $conn_rjllearning_specific, $search_string, $userid, $branch_id, $conn_rjllearning, $function_type, $limit, null);
        successreturn($success);
    }

    // $institution_id = trim($postdata['institution_id']);
    // $marksheets = fetchTemplates_details($institution_id, $conn_rjllearning_specific, $userid, $branch_id, $conn_rjllearning, $function_type, $limit, $offset);
    // successreturn($marksheets);
}
