<?php

function get_solution_users($conn_rjllearning, $workspace_id, $search_string, $current_user_role, $limit, $offset)
{
    try {
        $sql_count = "SELECT count(*) as total_rows FROM users where workspace_id = ? AND rejoice_solution_id IS NOT NULL";
        $array_params = [$workspace_id];

        if ($search_string != null) {
            $sql_count .= " AND (name LIKE ? OR username LIKE ? OR email LIKE ?)";
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
        }

        if ($current_user_role === 'superadmin') {
            $sql_count .= " AND (role = 'superadmin' OR role = 'admin' OR role = 'subadmin')";
        } elseif ($current_user_role === 'admin') {
            $sql_count .= " AND (role = 'superadmin' OR role = 'admin' OR role = 'subadmin')";
        }

        $stmt = $conn_rjllearning->prepare($sql_count);
        $stmt->execute($array_params);
        $result_total = $stmt->fetchAll();
        $totalrows = $result_total[0]['total_rows'];

        if ($limit == 'all') {

            $sql_users = "SELECT * FROM users where workspace_id =? AND rejoice_solution_id IS NOT NULL";
            $fetch_params = [$workspace_id];

            if ($search_string != null) {
                $sql_users .= " AND (name LIKE ? OR username LIKE ? OR email LIKE ?)";
                $fetch_params[] = '%' . $search_string . '%';
                $fetch_params[] = '%' . $search_string . '%';
                $fetch_params[] = '%' . $search_string . '%';
            }

            if ($current_user_role === 'superadmin') {
                $sql_users .= " AND (role = 'superadmin' OR role = 'admin' OR role = 'subadmin')";
            } elseif ($current_user_role === 'admin') {
                $sql_users .= " AND (role = 'superadmin' OR role = 'admin' OR role = 'subadmin')";
            }

            $sql_users .=  " order by date_time_created desc ";
        } else {
            $sql_users = "SELECT * FROM users where workspace_id =? AND rejoice_solution_id IS NOT NULL";
            $fetch_params = [$workspace_id];

            if ($search_string != null) {
                $sql_users .= " AND (name LIKE ? OR username LIKE ? OR email LIKE ?)";
                $fetch_params[] = '%' . $search_string . '%';
                $fetch_params[] = '%' . $search_string . '%';
                $fetch_params[] = '%' . $search_string . '%';
            }

            if ($current_user_role === 'superadmin') {
                $sql_users .= " AND (role = 'superadmin' OR role = 'admin' OR role = 'subadmin')";
            } elseif ($current_user_role === 'admin') {
                $sql_users .= " AND (role = 'superadmin' OR role = 'admin' OR role = 'subadmin')";
            }

            $sql_users .= " order by date_time_created desc ";
            $sql_users .= "LIMIT " . $offset . " ," . $limit . "";
        }

        $stmt = $conn_rjllearning->prepare($sql_users);
        $stmt->execute($fetch_params);
        $session_rows = $stmt->fetchAll();

        $array_return = [];

        foreach ($session_rows as $rows) {

            $formatted_date = date('Y-m-d H:i:s', $rows['date_time_created']);
            if ($rows['product_access_grant_time'] != null) {
                $product_access_grant_time = date('Y-m-d H:i:s', $rows['product_access_grant_time']);
            } else {
                $product_access_grant_time = null;
            }

            if ($rows['profile'] != null and !is_array($rows['profile'])) {
                $profile_attachment = json_decode($rows['profile'], true);
                $filePath = $profile_attachment['filepath'];
                $originalName = $profile_attachment['original_name'];
                $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                $final_array_attachment   = array("filepath" => $aws_attachment, "original_name" => $originalName);
            } else {
                $final_array_attachment =  null;
            }

            $array_return[] = array(
                'id' => $rows['id'],
                'workspace_id' => $rows['workspace_id'],
                'institution_id' => $rows['institution_id'],
                'branch_id' => $rows['branch_id'],
                'name' => $rows['name'],
                'dob' => $rows['dob'],
                'gender' => $rows['gender'],
                'username' => $rows['username'],
                'email' => $rows['email'],
                'mobile' => $rows['mobile'],
                'role' => $rows['role'],
                'designation' => $rows['designation'],
                'product_access_grant_time' => $product_access_grant_time,
                "profile" => $final_array_attachment,
                'date_time_created' => $formatted_date,
                'rejoice_solution_id' => $rows['rejoice_solution_id'],
                'status' => $rows['status'],
                'can_activate' => $rows['can_activate'],
            );
        }

        if (count($session_rows) < 50) {
            return array('total_rows' => $totalrows, 'solution_user_info' => $array_return, 'maxreach' => 1);
        } else {
            return array('total_rows' => $totalrows, 'solution_user_info' => $array_return, 'maxreach' => 0);
        }
    } catch (Exception $e) {
        errorreturn("Error: " . $e->getMessage());
        return;
    }
}

function fetchSpecific_solution_users($conn_rjllearning, $id, $workspace_id)
{
    try {
        $sql = $conn_rjllearning->prepare("SELECT * FROM users where id = ? and workspace_id = ?");
        $sql->execute(array($id, $workspace_id));
        $rows = $sql->fetchAll();

        if (count($rows) == 1) {

            $formatted_date = date('Y-m-d H:i:s', $rows[0]['date_time_created']);
            if ($rows[0]['product_access_grant_time'] != null) {
                $product_access_grant_time = date('Y-m-d H:i:s', $rows[0]['product_access_grant_time']);
            } else {
                $product_access_grant_time = null;
            }

            return array(
                'id' => $rows[0]['id'],
                'workspace_id' => $rows[0]['workspace_id'],
                'name' => $rows[0]['name'],
                'dob' => $rows[0]['dob'],
                'gender' => $rows[0]['gender'],
                'username' => $rows[0]['username'],
                'email' => $rows[0]['email'],
                'mobile' => $rows[0]['mobile'],
                'role' => $rows[0]['role'],
                'designation' => $rows[0]['designation'],
                'product_access_grant_time' => $product_access_grant_time,
                'date_time_created' => $formatted_date,
                'rejoice_solution_id' => $rows[0]['rejoice_solution_id'],
                'status' => $rows[0]['status'],
                'can_activate' => $rows[0]['can_activate']
            );
        } else {
            errorreturn("Enter valid User ID");
        }
    } catch (Exception $e) {
        errorreturn("Error: " . $e->getMessage());
        return;
    }
}
