<?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);
error_log(print_r($postdata, true));

checkIfNoPhpContentsReceive();

if (
 
    !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,["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 fetchAll_marksheets($institution_id, $conn_rjllearning_specific, $conn_rjllearning, $marksheet_id) {
    $static_path = 'https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/';

    // Fetch marksheet info based on institution and marksheet ID
    $sql = "SELECT * FROM marksheet 
            WHERE institution_id = ? AND id = ?";
    
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$institution_id, $marksheet_id]);
    $result_total = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $marksheets = [];

    foreach ($result_total as $row) {
        // Fetch template info based on institution ID and marksheet ID
        $sql = "SELECT preview_image, template_name
                FROM template_info 
                WHERE (institution_id = ? OR institution_id IS NULL) AND id = ?";
        
        $stmt = $conn_rjllearning->prepare($sql);
        $stmt->execute([$institution_id, $row['template_id']]);
        $template_result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Fetch marksheet info based on institution ID
        $sql = "SELECT *
                FROM marksheet_info
                WHERE (institution_id = ? OR institution_id IS NULL) AND marksheet_id = ?";
        
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$institution_id, $row['id']]);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);  // Fetching as associative array

        // Initialize an array to hold flattened rows
        $rows = [];

        foreach ($result as $entry) {
            // Get branch info
            if ($entry['branch_id'] == 'all') {
        $branch = array('branch_id' => $entry['branch_id'], 'branch_name' => ucwords($entry['branch_id']));
    } else {
        $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $entry['branch_id']);
    }

    // Get class info
    if ($entry['class_id'] == 'all') {
        $class = array('class_id' => $entry['class_id'], 'class_name' => ucwords($entry['class_id']));
    } else {
        $class = getClass($conn_rjllearning_specific, $institution_id, $entry['class_id']);
    }

    // Get section info
    // if ($entry['section_id'] == 'all') {
    //     $section = array('section_id' => $entry['section_id'], 'section_name' => ucwords($entry['section_id']));
    // } else {
    //     $section = getSection($conn_rjllearning_specific, $institution_id, $entry['section_id']);
    // }

            // Append flattened data to the rows array
            $rows[] = [
                'branch_id' => $branch,  // Ensure you adjust the key based on the structure returned by getBranchInfo
                'class_id' => $class,  // Adjust as necessary
                // 'section_id' => $section,  // Adjust as necessary
                'status' => $entry['status']
            ];
        }

        // Check if template result exists to avoid errors
        $preview_image_path = isset($template_result['preview_image']) ? 
            $static_path . $template_result['template_name'] . '/' . $template_result['preview_image'] : '';

        $marksheets[] = [
            'marksheet_id' => $row['id'],
            'template_id' => $row['template_id'],
            'preview' => $preview_image_path,
            'examination' => $row['examination_name'],
            'academic_session' => $row['academic_session'],
            'created_on' => $row['date_created'],
            'created_by' => $row['added_by'],
            'rows' => $rows  // Include the flattened rows array here
        ];
    }

    return $marksheets;
}



if ($postdata['function_type'] == "fetch_specific_marksheets") {
    // $institution_id = trim($postdata['institution_id']);
    $marksheet_id = isset($postdata['marksheet_id']) ? trim($postdata['marksheet_id']) : null;
    $marksheets = fetchAll_marksheets($institution_id, $conn_rjllearning_specific, $conn_rjllearning, $marksheet_id);
    successreturn($marksheets);
}

