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

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.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';
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);
// print_r($postdata);
checkIfNoPhpContentsReceive();


if (
    !isset($postdata['staff_support_id']) or !checkIfIssetAndNotEmpty($postdata['staff_support_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 iin decodede 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, ["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 getSpecificStaffAccessSupport($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $staff_support_id)
{
    // Prepare and execute the SQL query to fetch announcement data
    $sql = $conn_rjllearning_specific->prepare("SELECT * FROM staff_access_support WHERE id = ? AND institution_id = ?");
    $sql->execute(array($staff_support_id, $institution_id));
    $rows = $sql->fetchAll();

    if (count($rows) == 1) {
        $row = $rows[0];

        $function_code_json = $row['function_code'];
        $function_details = [];
        if (!empty($function_code_json)) {
            $function_codes = json_decode($function_code_json, true);
            if (is_array($function_codes)) {
                // Create placeholders for the SQL IN clause
                $placeholders = rtrim(str_repeat('?,', count($function_codes)), ',');
                $sql = "SELECT id, function_label,code,group_label FROM function_codes WHERE id IN ($placeholders)";
                $stmt = $conn_rjllearning->prepare($sql);
                $stmt->execute($function_codes);
                $function_data = $stmt->fetchAll();
                foreach ($function_data as $function) {
                    $function_details[] = [
                        'function_code_id' => $function['id'],
                        'function_label' => $function['function_label'],
                        'group_label' => $function['group_label'],
                        'code' => $function['code'],
                    ];
                }
            }
        }

        // Fetch faculty name
        $faculty_id = $row['faculty_id']; // The faculty_id from your data
        $faculty_sql = "SELECT name FROM faculty_info WHERE id = ?";
        $stmt = $conn_rjllearning_specific->prepare($faculty_sql);
        $stmt->execute([$faculty_id]);
        $faculty_info = $stmt->fetch();
        $faculty_name = $faculty_info['name'] ?? 'N/A';

        // Decode class_sections from JSON and process them
        $class_sections_json = $row['class_sections'];
        $class_sections = json_decode($class_sections_json, true);
        $formatted_sections = [];

        foreach ($class_sections as $section) {
            // Trim and handle class_id and convert to integer
            $class_id = (int)trim($section['class_id']); // Convert class_id to integer

            // Handle section_id (it can be a string or an array)
            if (is_array($section['section_id'])) {
                $section_ids = $section['section_id']; // Already an array, no need to explode
            } else {
                $section_ids = explode(',', trim($section['section_id'])); // Convert string to array
            }

            // Fetch class info
            if ($class_id === 0) { // Assuming 'all' translates to 0 for integer representation
                $class_info = ['id' => 'all', 'name' => 'All Classes']; // Add both ID and name as integers
            } else {
                $class_info = getClass($conn_rjllearning_specific, $institution_id, $class_id);
            }

            // Prepare the formatted class info
            $formatted_class = [
                'class_id' => $class_info['id'] ?? $class_id, // Ensure this is an integer
                'class_name' => $class_info['class_name'] ?? 'N/A' // Fetch class name
            ];

            // Fetch section info
            if (in_array('all', $section_ids)) {
                $formatted_sections[] = [
                    'class_id' => $formatted_class,
                    'section_id' => [['section_id' => 'all', 'section_name' => 'All Sections']] // All sections as integers
                ];
            } else {
                $formatted_section_info = []; // Array to hold section info
                foreach ($section_ids as $id) {
                    $section_info = getSection($conn_rjllearning_specific, $institution_id, trim($id));

                    // Prepare the formatted section info, ensuring section_id is an integer
                    $formatted_section_info[] = [
                        'section_id' => (int)($section_info['id'] ?? $id), // Ensure this is an integer
                        'section_name' => $section_info['section_name'] ?? 'N/A'
                    ];
                }

                // Add formatted section info to the result array
                $formatted_sections[] = [
                    'class_id' => $formatted_class,
                    'section_id' => $formatted_section_info // Add all section info
                ];
            }
        }

        // The $formatted_sections array now contains both class and section IDs and names.

        // The $formatted_sections array now contains the class and section names.

        // Fetch branch info
        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']);

        // Return the result as an array
        return [
            'staff_support_id' => $row['id'],
            'branch_info' => $branch_info,
            'faculty_name' => $faculty_name,
            'function_code' => $function_details,
            'class_sections' => $formatted_sections,
            'date_created' => $row['date_created'] // Correctly fetch the date_created
        ];
    } else {
        errorreturn("Enter Invalid support_staff info.");
    }
}

// Calling the function if the postdata function type is "fetch_specific_announcement"
if ($postdata['function_type'] == "fetch_specific_support_staff") {
    $staff_support_id = trim($postdata['staff_support_id']);
    $institution_id = trim($postdata['institution_id']);

    $success['data'] = getSpecificStaffAccessSupport($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $staff_support_id);
    successreturn($success);
}
