<?php
//base path learning to resources

require_once '../base_path_include.php';
require_once $base_path_to_learning_resources . "/includes/connect.php";;
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

$data = json_decode(file_get_contents('php://input'), true);

validateCurlSignature($data['api_signature']);


$rows = $data['user'];

$userid = $rows['userid'];
$name = $rows['name'];
$dob = $rows['dob'];
$gender = $rows['gender'];
if($rows['role'] == null){
    $user_role = 'subadmin'; 
}else{
    $user_role = $rows['role']; 
}
$username =  $rows['email'];
$email = $rows['email'];
$mobile = $rows['mobile'];
$workspace_id = $rows['workspace_id'];
$designation = $rows['designation'];
$status = $rows['status']; //if status is blocked then block status and can activate
$function_type = $rows['function_type'];

$excute_sql = $conn_rjllearning->prepare("SELECT can_activate FROM users WHERE rejoice_solution_id != ? and  workspace_id = ? and (username= ? or email = ?) ");
$excute_sql->execute(array($userid, $workspace_id, $username, $email));
$result_users = $excute_sql->fetchAll();
if (count($result_users) >= 1) {
    return false;
}

$sql = $conn_rjllearning->prepare("SELECT status, can_activate FROM users WHERE rejoice_solution_id = ? and  workspace_id = ?");
$sql->execute(array($userid, $workspace_id));
$users = $sql->fetchAll();
if (count($users) == 1) {
    if ($status == 0) {
        $status = 0;
        $can_activate = '0';
    } else if ($status == 1) {
        $status = 1;
        $can_activate = '1';
        // // $can_activate = '1'; //if can activate true then do not change user status
        // $can_activate = $users[0]['can_activate'];
        // $status = $users[0]['status']; 
        // // $status = 1;
    }
}

if ($function_type == 'alter_user') {
    if($user_role == 'superadmin'){
        // the username of super admin is his / her email id only.
        $sql = "UPDATE users SET  name=?, dob=?, gender=?,username= ?,email=?,mobile=?,role=?, designation=?,status=?,can_activate =? WHERE rejoice_solution_id=? and workspace_id  =?";
        $conn_rjllearning->prepare($sql)->execute(array($name, $dob, $gender, $username, $email, $mobile, $user_role, $designation, $status, $can_activate, $userid, $workspace_id));
    }else{
        $sql = "UPDATE users SET  name=?, dob=?, gender=?,email=?,mobile=?,role=?, designation=?,status=?,can_activate =? WHERE rejoice_solution_id=? and workspace_id  =?";
        $conn_rjllearning->prepare($sql)->execute(array($name, $dob, $gender, $email, $mobile, $user_role, $designation, $status, $can_activate, $userid, $workspace_id));
    }
    
}

return true;
