<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\User;
use App\Models\UserLog;

use App\Http\Rules\User\Image64Check;

use App\Http\Helpers\General;
use App\Http\Helpers\Hasher;
use App\Http\Helpers\ImageHandel;
use Carbon\Carbon;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

use App\Http\Controllers\User\BaseController;

class UserModule extends BaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    public static function self(Request $request)
    {
    	$self = Auth::guard('user-api')->user();

    	$data = General::returnData($self, true);
        return response()->json($data);
    }

    public static function update(Request $request)
    {
        $id = Auth::guard('user-api')->user()->id;
        $validation = UserModule::validation($request, $id, 'PUT');
        if (!$validation->status) {
            return response()->json($validation, 422);
        }

        DB::beginTransaction();

        $first_name = $request->input('first_name');
        $last_name = $request->input('last_name');
        $email = $request->input('email');
        $password = $request->input('password');
        $status = $request->input('status');

        $user = User::find($id);
        $user->first_name = $first_name ?? $user->first_name;
        $user->last_name = $last_name ?? $user->last_name;
        $user->email = $email ?? $user->email;
        if (!empty($password)) {
            $user->password = bcrypt($password);
        }
        $user->status = $status ?? 2;

        // img
        $img = $request->input('img');
        if (!empty($img)) {
            $remove_image = $user->img;
            $remove_image = $remove_image ? ImageHandel::removeImage($remove_image) : '';
            $img = json_encode(ImageHandel::insertImage('user', $img));
            $user->img = $img;
            if (!$img) {
                DB::rollBack();
            }
        }

        $user->update();

        // log
        UserModule::makeLog($user->id, 'user (' . Auth::guard('user-api')->user()->id . ') updated');

        DB::commit();

        $query_string = General::getCachePerviousQuery('admin_query');
        $data = General::returnData($user, $query_string);

        return response()->json($data);
    }

    public static function validCheck(Request $request, $hash_id = '', $method = 'POST')
    {
        $id = Auth::guard('user-api')->user()->id;
        $validation = UserModule::validation($request, $id, $method);
        if (!$validation->status) {
            return response()->json($validation, 422);
        }
    }

    private static function validation(Request $request, $id = '', $method = 'POST')
    {
        $data = $request->all();
        $rule= [];

        if ($method == 'PUT') {
            $rule = [
                'img' => '',
                'first_name' => 'required',
                'last_name' => 'required',
                'email' => 'required|email|max:255|unique:users,email,' . $id,
                'password' => 'sometimes|confirmed',
            ];
        }

        if (!empty($data['img'])) {
            foreach ($data['img'] as $key => $row) {
                $rule['img'.'.'.$key] = ['required', new Image64Check()];
            }
        }

        $validator = Validator::make($data, $rule, config('error_code'));

        $errors = $validator->errors();

        if (!empty($data['img'])) {
            foreach ($data['img'] as $key => $row) {
                if ($errors->first('img'.'.'.$key)) {
                    $errors->add('img', config('error_code.img_error'));
                    break;
                }
            }
        }

        if ($validator->fails()) {
            $data = General::returnErrorData($errors);
            return $data;
        }
        else {
            return (object)['status' => true];
        }
    }

    public static function makeLog($id = '', $remark = '') 
    {
        $user = User::find($id);
        $user_log = new UserLog();
        $user_log->user_id = $user->id;
        $user_log->history = json_encode($user);
        $user_log->remark = $remark;
        $user_log->save();
    }
}
