<?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_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/common_modules/fun_tasks/speech_assessment/function.php';

$postdata=$_POST;

// Initial required fields check
if (!isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])) {
    errorreturn("All * fields are required.");
}

// Only allow 'create_speech_task'
$function_type = trim($postdata['function_type']);
if ($function_type !== 'delete_speech_task') errorreturn("Invalid function_type.");

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;

// User access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin','admin','teacher','principal'], null);
if (!$specific_db_name) errorreturn('Access denied.');
$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

// Assign variables
$institution_id = trim($postdata['institution_id']);
$task_id        = trim($postdata['task_id']);

// Call deleteSpeechTask
$result = deleteSpeechTask(
    $conn_rjllearning,
    $workspace_id,
    $institution_id,
    $task_id,
    $username,
    $role
);

// Handle response
if ($result) {
    successreturn([
        'message' => $result,
        'task_id' => $task_id
    ]);
} else {
    errorreturn('Something went wrong while deleting the Speech Task.');
}
?>
