<?php

ini_set('display_errors', 1);

// Include necessary files
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';

// Decode JSON input data
$postdata = json_decode(file_get_contents("php://input"), true);

// Check if no data was received
checkIfNoPhpContentsReceive();

// Validate required fields
$requiredFields = ['branch_id', 'institution_id', 'api_signature', 'function_type', 'jwt_token'];
foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.$field");
    }
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Authenticate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
// Extract user details from JWT token
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

// Validate user access and get specific database name
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

// Sanitize input data
$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);

$homework_setting = (int)($postdata['homework_setting']);

$time = isset($postdata['homework_time']) ? trim($postdata['homework_time']) : null;

if (!in_array($homework_setting, [0, 1])) {
    errorreturn("Invalid homework_setting value. Must be 0 or 1.");
}

// Validate time only if homework_setting is 1
if ($homework_setting === 1 && empty($time)) {
    errorreturn("Time must be provided when homework_setting is 1.");
}

$check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$check_academic_confirmation) {
    errorreturn("Access denied. Academic session not active.");
}

$isBranchClassSubjectValid = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, null, null, $institution_id);
if (!$isBranchClassSubjectValid) {
    errorreturn("Invalid branch_id.");
}

// Prepare JSON data for homework_setting
if ($homework_setting == 0) {
    // If homework_setting is 0, no time should be included
    $homeworkSettingData = json_encode([
        "homework_setting" => $homework_setting
    ]);
} else {
    // If homework_setting is 1, include time
    $homeworkSettingData = json_encode([
        "homework_setting" => $homework_setting,
        "homework_time" => $time
    ]);
}

// Update homework setting
if ($postdata['function_type'] == "update_homework_setting") {
    $sql = "UPDATE institution_global_settings 
            SET homework_setting = ?, 
                last_modified_by = ?, 
                last_updated_time = ? 
            WHERE institution_id = ? AND branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $last_updated_time = date("Y-m-d H:i:s");
    $stmt->execute([
        $homeworkSettingData,
        $username,
        $last_updated_time,
        $institution_id,
        $branch_id
    ]);
    successreturn("Homework setting updated successfully.");
}
