<?php

namespace Miladmodaresi\Taamito\Api;

use WC_Product;
use WP_Error;
use WP_REST_Request;

/**
 * The Singleton class defines the `GetInstance` method that serves as an
 * alternative to constructor and lets clients access the same instance of this
 * class over and over.
 */
class User
{
    public function create(WP_REST_Request $request)
    {
        $user = $request->get_body_params();
        // $files = $request->get_file_params();
        $fullName = $user['name'] . '_' . $user['family'];
        $fullName = str_replace(' ', '', $fullName);

        $userModel = wp_insert_user(
            [
                'user_login' => $user['mobile'] ?? $fullName,
                'phone'      => $user['mobile'] ?? null,
                'email'      => $user['email'] ?? (taamitoGenerateRandomString(10) . '@exam.com'),
                'user_pass'  => taamitoGenerateRandomString(20),
                'first_name' => $user['name'],
                'last_name'  => $user['family'],
            ]
        );
        if ($userModel instanceof WP_Error)
            $userModel = wp_insert_user(
                [
                    'user_login' => ($user['mobile'] ?? $fullName) . taamitoGenerateRandomString(5),
                    'phone'      => $user['mobile'] ?? null,
                    'email'      => $user['email'] ?? (taamitoGenerateRandomString(10) . '@exam.com'),
                    'user_pass'  => taamitoGenerateRandomString(20),
                    'first_name' => $user['name'],
                    'last_name'  => $user['family'],
                ]
            );
        $user = get_user_by('id', $userModel);
        return taamitoApp()->view($user);
    }
    public function update(WP_REST_Request $request)
    {
        $user = $request->get_body_params();
        $fullName = $user['name'] . '_' . $user['family'];
        $fullName = str_replace(' ', '', $fullName);

        $data =             [
            'ID'         => $user['id'],
            'user_login' => $user['mobile'] ?? $fullName,
            'phone'      => $user['mobile'] ?? null,
            'first_name' => $user['name'],
            'last_name'  => $user['family'],
        ];

        $userModel = wp_update_user($data);

        $user = get_user_by('id', $userModel);
        return taamitoApp()->view($user);
    }
    public function delete(WP_REST_Request $request)
    {
        $params = $request->get_query_params();
        wp_delete_user($params['id']);
        return taamitoApp()->view([]);
    }
}
