<?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";

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;

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

function fetchTemplates_details($institution_id, $conn_rjllearning_specific, $search_string, $limit, $offset)
{
    try {

        $sql_count = "SELECT count(*) as total_rows FROM marksheet_info mi INNER JOIN marksheet m ON mi.marksheet_id = m.id WHERE mi.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 = ?";
            $array_params = [$institution_id];

            if ($search_string != null) {
                $sql_marksheet_info .= " 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 . '%';
            }
        } 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 = ?";
            $array_params = [$institution_id];

            if ($search_string != null) {
                $sql_marksheet_info .= " 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 . '%';
            }

            $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 (isset($processed_marksheets[$marksheet_id])) {
                continue;
            }

            $sql_marksheet = "SELECT academic_session, marksheet_name, 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 (!$marksheet_data) {
                continue;
            }

            $filtered_rows = array_filter($marksheet_info_data, function ($r) use ($marksheet_id) {
                return $r['marksheet_id'] == $marksheet_id;
            });

            $branch_ids = array_unique(array_column($filtered_rows, 'branch_id'));
            $class_ids = array_unique(array_column($filtered_rows, 'class_id'));

            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';
            }

            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';
            }

            $marksheets[] = [
                'marksheet_id' => $marksheet_id,
                'examination' => $marksheet_data['examination_name'],
                'academic_session' => $marksheet_data['academic_session'],
                'marksheet_name' => $marksheet_data['marksheet_name'],
                'branch' => $branch_info,
                'class' => $class_info,
                'created_on' => $marksheet_data['date_created'],
                'created_by' => $marksheet_data['added_by']
            ];

            $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") {
    $institution_id = trim($postdata['institution_id']);
        $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }
    
    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, $limit, $offset);
        successreturn($success);
    } else {
        $success['data'] = fetchTemplates_details($institution_id, $conn_rjllearning_specific, $search_string, $limit, null);
        successreturn($success);
    }
}
