<?php
// Enable error display for debugging
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.");
    }
}

// Validate OTP settings
if (!isset($postdata['otp_setting'])) {
    errorreturn("OTP settings are required.");
}

$otp_setting = $postdata['otp_setting'];
$otp_fields = [
    'students_password_reset_otp' => [1, 2, 3], // 1 for OTP on Mail and SMS, 2 for OTP only on Mail, 3 for OTP only on SMS
    'faculty_password_reset_otp' => [1, 2, 3],  // 1 for OTP on Mail and SMS, 2 for OTP only on Mail, 3 for OTP only on SMS
    'inventory_sale_otp' => [1, 2, 3],  // 1 for OTP on Mail and SMS, 2 for OTP only on Mail, 3 for OTP only on SMS
    'gate_pass_otp' => [0, 1]  // 1 for yes, 0 for no
];

foreach ($otp_fields as $field => $valid_values) {
    if (!isset($otp_setting[$field]) || !in_array($otp_setting[$field], $valid_values)) {
        errorreturn("Invalid value for $field. Must be " . implode(', ', $valid_values) . ".");
    }
}

// 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,['superadmin','admin','principal','teacher'], 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']);

// Validate and process homework_setting
// $homework_setting_data = $postdata['homework_setting'];
// if (!isset($homework_setting_data['homework_setting']) || !in_array($homework_setting_data['homework_setting'], [0, 1])) {
//     errorreturn("Invalid homework_setting value. Must be 0 or 1.");
// }

// if ($homework_setting_data['homework_setting'] === 1) {
//     if (!isset($homework_setting_data['homework_time']) || empty(trim($homework_setting_data['homework_time']))) {
//         errorreturn("Time must be provided when homework_setting is 1.");
//     }
//     $homework_time = trim($homework_setting_data['homework_time']);
// } else {
//     $homework_time = null;
// }

// // Prepare JSON data for homework_setting
// $homeworkSettingData = json_encode([
//     "homework_setting" => $homework_setting_data['homework_setting'],
//     "homework_time" => $homework_time
// ]);

// Create the OTP settings array
$otp_settings_array = [
    'students_password_reset_otp' => $otp_setting['students_password_reset_otp'], 
    'faculty_password_reset_otp' => $otp_setting['faculty_password_reset_otp'],
    'inventory_sale_otp' => $otp_setting['inventory_sale_otp'],
    'gate_pass_otp' => $otp_setting['gate_pass_otp']
];

$otp_setting_json = json_encode($otp_settings_array); // JSON encode the OTP settings

// Check if academic session is active
$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.");
}

if ($postdata['function_type'] == "update_otp_setting") {
    $sql = $conn_rjllearning_specific->prepare("SELECT id FROM branch WHERE id = ? AND institution_id = ?");
    $sql->execute([$branch_id, $institution_id]);
    $result = $sql->fetchAll();
    if (count($result) != 1) {
        errorreturn("Branch not found.");
    }

    // Update setting
    $sql = "UPDATE institution_global_settings SET otp_setting = ?, last_modified_by=?, last_updated_time=? WHERE institution_id = ? AND branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);

    // Get the current timestamp and format it as a date string
    $last_updated_time = date("Y-m-d H:i:s", time());

    // Execute the SQL query with the formatted date string
    $stmt->execute([ $otp_setting_json, $username, $last_updated_time, $institution_id, $branch_id]);

    // Return success message
    successreturn("Updated institution global settings successfully.");
} else {
    errorreturn("Invalid Function Type");
}
