<?php

ini_set('display_errors', 1);

require_once '../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/functions/functions.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'user_management/solution_user_management/function.php';


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

if (
    !isset($postdata['id']) or !checkIfIssetAndNotEmpty($postdata['id']) or
    !isset($postdata['status']) or (!is_numeric($postdata['status']) && !checkIfIssetAndNotEmpty($postdata['status'])) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type']) or
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$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;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin', 'admin'], null);

function update_user_status($conn_rjllearning, $id, $status, $role) {
    try {
        
        $sql_get_role = "SELECT role FROM users WHERE id = ?";
        $stmt = $conn_rjllearning->prepare($sql_get_role);
        $stmt->execute([$id]);
        $user = $stmt->fetch();
        
        if (!$user) {
            errorreturn("User not found");
        }

        $target_user_role = $user['role'];

        // Check permissions based on current user's role
        $can_update = false;
        
        if ($role === 'superadmin') {
            $can_update = true;
        } elseif ($role === 'admin') {
            $can_update = ($target_user_role === 'subadmin');
        }

        if (!$can_update) {
            errorreturn("Permission denied");
        }
        
        if (!in_array($status, [0, 1])) {
            errorreturn("Invalid status value");
        }

        // Update the status
        $sql_update = "UPDATE users SET status = ? WHERE id = ?";
        $stmt = $conn_rjllearning->prepare($sql_update);
        $result = $stmt->execute([$status, $id]);

        if ($result) {
            return "Status updated successfully";
        } else {
            return "Failed to update status";
        }
        
    } catch (Exception $e) {
        error_log("Error updating user status: " . $e->getMessage());
        return ['success' => false, 'message' => 'An error occurred'];
    }
}

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

    $id = $postdata['id'];
    $status = $postdata['status'];

    $success = update_user_status($conn_rjllearning, $id, $status, $role);
    successreturn($success);
}
