<?php

// Set up error reporting
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_resources . 'includes/specific_db_config.php';

$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

$required_fields = ['institution_id', 'branch_id','test_id', 'api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}

validateApiSignature($postdata['api_signature']);
// Authenticate user and get user details
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$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;

// Validate user access to specific database
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

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

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

// either the user has to fill gst or pan or ledgerhead 
function deleteTestQuestions($conn_rjllearning_specific, $institution_id, $branch_id, $test_id)
{
    
     $sql_test = "SELECT count(*) as total FROM test_submission WHERE test_id = ? and  institution_id=? and branch_id =? ";
    $stmt_test = $conn_rjllearning_specific->prepare($sql_test);
    $stmt_test->execute(array($test_id, $institution_id, $branch_id));
    $result_test = $stmt_test->fetchAll();
    if ($result_test[0]['total'] >= 1) {

        errorreturn("Unable to delete test because of the presence in test questions.");
    }
    
    $sql_submission = "SELECT count(*) as total FROM test_submission WHERE test_id = ? and  institution_id=? and branch_id =? ";
    $stmt_submission = $conn_rjllearning_specific->prepare($sql_submission);
    $stmt_submission->execute(array($test_id, $institution_id, $branch_id));
    $result_submission = $stmt_submission->fetchAll();
    if ($result_submission[0]['total'] >= 1) {

        errorreturn("Unable to delete test because of the presence in test submisson.");
    }
 
    
    $sql = "DELETE FROM test WHERE id = ? and  institution_id=? and branch_id =? ";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute(array($test_id, $institution_id, $branch_id));
    $count = $stmt->rowCount();
    if ($count = 1) {
        return "Delete test Successfully";
    } else {
        errorreturn("unable to delete test");
    }
}



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

//   $branch_id = trim($postdata['branch_id']);
   $test_id = trim($postdata['test_id']);
   $academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
   if ($academic_id == false) {
       errorreturn("Access denied. Academic session not active.");
   }

    $success['data'] = deleteTestQuestions($conn_rjllearning_specific, $institution_id, $branch_id, $test_id);
    successreturn($success);
}

