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

//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();
// print_r($postdata);die();
if (
    !isset($postdata['faculty_id']) or !checkIfIssetAndNotEmpty($postdata['faculty_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,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
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 . '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);

$faculty_id = trim($postdata['faculty_id']);

$res = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE id = ? AND institution_id = ?");
$res->execute([$faculty_id, $institution_id]);
$result = $res->fetchAll();

// Check if faculty_id exists
if (count($result) != 1) {
    errorreturn("Faculty with ID $faculty_id not found.");
}

$function_code=$postdata['function_code'];
$placeholders = implode(',', array_fill(0, count($function_code), '?'));

    // Prepare the SQL query to check if these function codes exist in the table
    $sql = "SELECT id FROM function_codes WHERE id IN ($placeholders)";
    $stmt = $conn_rjllearning->prepare($sql);

    // Execute the query with the institution_id and function_code values
    $params = array_merge($function_code);
    $stmt->execute($params);
    
    // Fetch all existing function codes
    $existing_codes = $stmt->fetchAll(PDO::FETCH_COLUMN);

    if (!empty($existing_codes)) {
        // Convert the array of valid function codes to a JSON string
        $valid_function_codes = json_encode($existing_codes);
    } else {
        $valid_function_codes = json_encode([]); // Return an empty array if no valid codes found
    }


if (!isset($postdata['class_sections'])) {
    errorreturn("class_sections are required.");
}

$class_sections = $postdata['class_sections'];

// Validate that class_sections is an array
if (!is_array($class_sections)) {
    errorreturn("Invalid class_sections format.");
}

foreach ($class_sections as $section) {
    if (!isset($section['class_id']) || !isset($section['section_id'])) {
        errorreturn("Each class_section must have class_id and section_id.");
    }

    $class_id = trim($section['class_id']);
    $section_id = $section['section_id']; // Do not trim here, check its type first

    // Check if the class_id is not 'all'
    if ($class_id !== 'all') {
        $res = $conn_rjllearning_specific->prepare("SELECT id FROM class_info WHERE id = ? AND institution_id = ?");
        $res->execute([$class_id, $institution_id]);
        $result1 = $res->fetchAll();
        if (count($result1) != 1) {
            errorreturn("Class with ID $class_id not found.");
        }
    }

    // Check if section_id is an array
    if (is_array($section_id)) {
        // Process each section_id within the array
        foreach ($section_id as $id) {
            $id = trim($id); // Trim each section_id element
            if ($id === 'all') continue; // Skip 'all' if you allow it to be a valid value

            // Ensure the section belongs to the given class_id
            $res = $conn_rjllearning_specific->prepare("SELECT id FROM section_info WHERE id = ?  AND institution_id = ?");
            $res->execute([$id, $institution_id]);
            $result2 = $res->fetchAll();
            if (count($result2) != 1) {
                errorreturn("Section with ID $id does not belong to Class ID $class_id.");
            }
        }
    } else {
        // Handle case where section_id is not an array (fallback)
        $section_id = trim($section_id); // Handle non-array case, trim it
        if ($section_id !== 'all') {
            // Check section_id as a single value
            $res = $conn_rjllearning_specific->prepare("SELECT id FROM section_info WHERE id = ? AND institution_id = ?");
            $res->execute([$section_id, $institution_id]);
            $result2 = $res->fetchAll();
            if (count($result2) != 1) {
                errorreturn("Section with ID $section_id does not belong to Class ID $class_id.");
            }
        }
    }
}

$class_sections_json = json_encode($class_sections);
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}


if ($postdata['function_type'] == "create_staff_access_support") {

    $res = $conn_rjllearning_specific->prepare("SELECT id FROM  staff_access_support WHERE institution_id = ?  AND branch_id = ?  AND faculty_id = ? ");
    $res->execute(array($institution_id, $branch_id,$faculty_id));
    $result1 = $res->fetchAll();

    if (count($result1) >= 1) {
        errorreturn("This staff access support already exists. ");
    }



    // Decode the class_sections JSON data from the request



// Proceed with storing the data
try {
    $sql = "INSERT INTO staff_access_support (institution_id, branch_id, faculty_id,function_code, class_sections, added_by, date_created, time_created, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?,?)";

    $stmt = $conn_rjllearning_specific->prepare($sql);

    $stmt->execute([
        $institution_id,
        $branch_id,
        $faculty_id,
        $valid_function_codes,
        $class_sections_json,
        $username, 
        date('Y-m-d'),
        time(),
        '1'
    ]);

    $id = $conn_rjllearning_specific->lastInsertId();
    updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
    successreturn(['id' => $id, 'successmsg' => "Successfully added staff access support."]);
} catch (Exception $e) {
    errorreturn("Error: " . $e->getMessage());
}

   
    
} else if ($postdata['function_type'] == "alter_support_staff") {
    if (!isset($postdata['staff_support_id']) || !checkIfIssetAndNotEmpty($postdata['staff_support_id'])) {
        errorreturn('Error in updating the support_staff.');
    } else {
        $id = $postdata['staff_support_id'];
    }

    // Fetch existing class_sections
    $stmt = $conn_rjllearning_specific->prepare("SELECT class_sections FROM staff_access_support WHERE id = ?");
    $stmt->execute([$id]);
    $existing_data = $stmt->fetch(PDO::FETCH_ASSOC);
    $existing_class_sections = json_decode($existing_data['class_sections'], true);

    // Check if new update is "all"
    $is_new_update_all = false;
    foreach ($class_sections as $section) {
        if ($section['class_id'] === 'all' && isset($section['section_id']) && is_array($section['section_id']) && in_array('all', $section['section_id'])) {
            $is_new_update_all = true;
            break;
        }
    }

    // Check if existing data is "all"
    $is_existing_all = false;
    if ($existing_class_sections) {
        foreach ($existing_class_sections as $section) {
            if ($section['class_id'] === 'all' && isset($section['section_id']) && is_array($section['section_id']) && in_array('all', $section['section_id'])) {
                $is_existing_all = true;
                break;
            }
        }
    }

    // Determine final class sections
    if ($is_new_update_all) {
        // If new update is "all", completely override existing data
        $final_class_sections = [['class_id' => 'all', 'section_id' => ['all']]];
    } elseif ($is_existing_all) {
        // If existing was "all" and new update is specific, replace with new data
        $final_class_sections = $class_sections;
    } else {
        // Merge existing and new data (append new entries)
        $final_class_sections = array_merge($existing_class_sections ?? [], $class_sections);
        
        // Remove exact duplicates (same class_id + same section_id)
        $unique = [];
        foreach ($final_class_sections as $section) {
            $key = $section['class_id'] . '-' . json_encode((array)$section['section_id']);
            $unique[$key] = $section;
        }
        $final_class_sections = array_values($unique);
    }

    $final_class_sections_json = json_encode($final_class_sections);

    $sql_users = "UPDATE staff_access_support SET class_sections=?, function_code=?, last_modified_by=? WHERE id=? AND institution_id=?";
    $conn_rjllearning_specific->prepare($sql_users)->execute([
        $final_class_sections_json,
        $valid_function_codes,
        $username,
        $id,
        $institution_id
    ]);

    updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
    successreturn("Updated staff access support Successfully");
}
