<?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/check_username_availability.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/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning_resources . 'lib/common_modules/fun_tasks/speech_assessment/function.php';

// $postdata = json_decode(file_get_contents("php://input"), true);
$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 !== 'create_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'], null);
if (!$specific_db_name) errorreturn('Access denied.');
$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

// Separate conditional fields from mandatory fields
$mandatory_fields = [
    'institution_id','branch_id','subject',
    'title','description','allowed_type','max_duration',
    'date_of_publish','function_type','api_signature','jwt_token',
    'last_date','description_attachment_type'
];
foreach ($mandatory_fields as $field) {
    if (!isset($postdata[$field]) || $postdata[$field] === '') {
        errorreturn("Field '{$field}' is required and cannot be empty.");
    }
}

// Conditional check for class/section or age
$has_class_info = (isset($postdata['class_id']) && $postdata['class_id'] !== '') && (isset($postdata['section_id']) && $postdata['section_id'] !== '');
$has_age_info = (isset($postdata['min_age']) && $postdata['min_age'] !== '') && (isset($postdata['max_age']) && $postdata['max_age'] !== '');

if (!$has_class_info && !$has_age_info) {
    errorreturn("Either 'class_id' and 'section_id' or 'min_age' and 'max_age' are required.");
}
$max_points =trim($postdata['max_points']) ?? null;
// Assign variables
$institution_id = trim($postdata['institution_id']);
$branch_id = $postdata['branch_id'];
$academic_id = $postdata['academic_id'];
$class_id = $postdata['class_id'];
$section_id = $postdata['section_id'];
$subject = trim($postdata['subject']);
$min_age = $postdata['min_age'];
$max_age = $postdata['max_age'];
$title = trim($postdata['title']);
$description = trim($postdata['description']);
$allowed_type = trim($postdata['allowed_type']);
$max_duration = $postdata['max_duration'];
$date_of_publish = $postdata['date_of_publish'];
$function_type = trim($postdata['function_type']);
$last_date = $postdata['last_date'];
$description_attachment_type = trim($postdata['description_attachment_type']);
$last_modified_by = $username ?? null;
$last_modified_at = date('Y-m-d H:i:s');

// File
$attachment = (isset($_FILES['description_attachment']) && !empty($_FILES['description_attachment']['tmp_name'])) 
    ? $_FILES['description_attachment'] 
    : null;

// Call createSpeechTask function
$task_id = createSpeechTask(
    $conn_rjllearning,
    $conn_rjllearning_specific,
    $workspace_id,
    $institution_id,
    $branch_id,
    $academic_id,
    $class_id,
    $section_id,
    $subject,
    $min_age,
    $max_age,
    $username,
    $title,
    $description,
    $allowed_type,
    $max_duration,
    $date_of_publish,
    $last_date,
    $last_modified_by,
    $last_modified_at,
    $s3_learning_bucket,
    $learning_bucketName,
    $role,
    $attachment,
    $description_attachment_type
);

if ($task_id) {
    successreturn([
        'task_id' => $task_id,
        'successmsg' => "Speech Task created successfully."
    ]);
} else {
    errorreturn('Something went wrong while creating the Speech Task.');
}
?>