<?php

namespace App\Services;

use App\Models\User;
use App\Repositories\CheckinHistoryRepository;
use App\Repositories\ImageFaceCaptureRepository;
use App\Repositories\UserRepository;
use App\Traits\Base64ToImage\SaveImageToFolder;
use App\Traits\Time\MakeTimeCheckinApi;
use DateTime;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use League\CommonMark\Block\Renderer\ThematicBreakRenderer;
use Throwable;
use App\Http\Controllers\Backend\ForwardController;

/**
 * Class UserService.
 */
class UserService extends BaseService
{
    use SaveImageToFolder;
    use MakeTimeCheckinApi;
    /**
     * @var UserRepository
     */
    protected $userRepository;

    /**
     * @var ImageFaceCaptureRepository
     */
    protected $imageFaceCaptureRepository;

    /**
     * @var CheckinHistoryRepository
     */
    protected $checkinHistoryRepository;

    /**
     * UserService constructor.
     * @param UserRepository             $userRepository
     * @param CheckinHistoryRepository   $checkinHistoryRepository
     * @param ImageFaceCaptureRepository $imageFaceCaptureRepository
     */
    public function __construct(
        UserRepository $userRepository,
        ImageFaceCaptureRepository $imageFaceCaptureRepository,
        CheckinHistoryRepository $checkinHistoryRepository
    ) {
        $this->userRepository = $userRepository;
        $this->imageFaceCaptureRepository = $imageFaceCaptureRepository;
        $this->checkinHistoryRepository = $checkinHistoryRepository;
//        \Log::info('■'.__CLASS__.'|'.__FUNCTION__.'|'.__LINE__.'|'.__FILE__);
    }

    /**
     * @param $params
     * @return mixed
     */
    public function getListUser($params)
    {
        if (
            empty($params['user_name']) || (!empty($params['user_name'])
                && mb_strlen($params['user_name']) <= 20)
        ) {
            return $this->returnSuccess($this->userRepository->getListUser($params));
        }

        return $this->returnSuccess();
    }

    /**
     * Create User
     * @param $attributes
     * @return mixed
     */
    public function createUser($attributes)
    {
        DB::beginTransaction();
        try {
            // $attributes['password'] = \Hash::make($attributes['password']);
            // $attributes['username'] = $this->generateUsername();
            $attributes['password'] = \Hash::make("12345678");
            // $attributes['username'] = $attributes['userName'];
            $attributes['pronunciation_ja'] = $attributes['name'];
            
            $user = $this->userRepository->createUser($attributes);
            if ($user) {
                !empty($attributes['is_admin']) ? $user->assignRole(config('boilerplate.access.role.admin'))
                    : $user->assignRole(config('boilerplate.access.role.user'));
                DB::commit();
                return $this->returnSuccess($user, __('string.create_user.create_success'));
            }

            return $this->returnError(__('string.create_user.create_fail'));
        } catch (\Exception $e) {
			\Log::error('■'.__CLASS__.'|'.__FUNCTION__.'|'.__LINE__.'|'.__FILE__.'|'.$e->getMessage());
            \Log::error("Error Create User: " . $e->getMessage());
            DB::rollBack();
            return $this->returnError(__('string.server.common.error'));
        }
    }

    /**
     * auto generate username
     * @return string
     */
    public function generateUsername()
    {
        $user = $this->userRepository->getLastUser();
        $username = is_numeric($user->username)
            ? $user->username + 1
            : $user->id + 1;

        return str_pad($username, ID_USER_LENGTH, "0", STR_PAD_LEFT);
    }

    /**
     * get user id
     * @param $userId
     * @return mixed
     */
    public function findUserById($userId)
    {
        return $this->userRepository->findUserById($userId);
    }

    /**
     * get user id
     * @param $params
     * @return mixed
     * @throws Throwable
     */
    public function changePassword($params)
    {
        DB::beginTransaction();
        try {
            if ($this->userRepository->changePassword($params)) {
                DB::commit();
                return $this->returnSuccess([], __('string.user.change-password.success'));
            }

            return $this->returnError(__('string.user.change-password.failed'));
        } catch (Throwable $e) {
			\Log::error('■'.__CLASS__.'|'.__FUNCTION__.'|'.__LINE__.'|'.__FILE__.'|'.$e->getMessage());
            \Log::info($e->getMessage());
            DB::rollBack();
            return $this->returnError(__('string.server.common.error'));
        }
    }

    /**
     * Update User
     * @param $attributes
     * @return mixed
     */
    public function updateUser(User $user, array $attributes = [])
    {
        $attributes['is_update_password'] = False;

        DB::beginTransaction();
        try {
            /**
             * if password is '********' , don't change password
             */
            
            if (!$attributes['is_update_password']) {
                unset($attributes['password']);
            } else {
                $attributes['password'] = \Hash::make($attributes['password']);
            }
            unset($attributes['is_update_password']);

            $attributes['id'] = $user->id;
            $roleAdmin = $attributes['is_admin'] ?? false;
            $attributes['new_role'] = $roleAdmin
                ? config('boilerplate.access.role.admin')
                : config('boilerplate.access.role.user');
            unset($attributes['is_admin']);
            $result = $this->userRepository->updateUser($attributes);
            $message = $roleAdmin ? __('string.update_user.update_admin_fail') : __('string.update_user.update_fail');
            if ($result) {
                $message = $roleAdmin
                    ? __('string.update_user.update_admin_success')
                    : __('string.update_user.update_success');
                DB::commit();
//K.Nakazaki 2022/03/30 Start
	            $dataSenApi = array();
	            $dataSenApi['id'] = $user->id;
	            $dataSenApi['images'] = array();
	            $faceImage = $this->imageFaceCaptureRepository->findUserUpload($user->id);
                if($faceImage){
                    foreach(FACE_DIRECTION as $key => $image) {
                        $filename = URL_IMAGE_FACE .'/'. $faceImage->$key;
                        if(Storage::disk('public')->exists($filename)) {
                            $dataSenApi['images'][$key] = base64_encode(Storage::disk('public')->get($filename));
                        }
                    }
                    if(count($dataSenApi['images']) == 9) {
                        $user = $this->userRepository->findUserById($user->id);
                        if($user) {
                            $dataSenApi['username'] = $user->username;
                            $dataSenApi['name'] = $user->name;
                            $dataSenApi['pronunciation_ja'] = $user->pronunciation_ja;
                        }
                        $responseApi = curlCallApiFaceBank(ForwardController::env('URL_REGISTER_FACE_IMAGE'), json_encode($dataSenApi));
                    }
                }
//K.Nakazaki 2022/03/30 End
                return $this->returnSuccess([], $message);
            }

            return $this->returnError($message);
        } catch (\Exception $e) {
			\Log::error('■'.__CLASS__.'|'.__FUNCTION__.'|'.__LINE__.'|'.__FILE__.'|'.$e->getMessage());
            \Log::error("Error Update User: " . $e->getMessage());
            DB::rollBack();
            return $this->returnError(__('string.server.common.error'));
        }
    }

    /**
     * Delete Model User.
     *
     * @param User $user
     * @return mix
     */
    public function delete(User $user)
    {
        DB::beginTransaction();
        try {
            if ($user->id === auth()->id()) {
                return $this->returnError(__('string.delete_user.you_can_not_delete_yourself'));
            }

            // if ($this->imageFaceCaptureRepository->checkUserRegisterFaceImage($user->id)) {
            //$responseApi = curlCallApiFaceBank(ForwardController::env('URL_DELETE_USER'), json_encode(['id' => $user->id]));
            $responseApi = curlCallApiFaceBank(ForwardController::env('URL_DELETE_USER'), json_encode(['id' => $user->username]));
            //     if ($responseApi['response'] != RESPONSE_OK) {
            //         return $this->returnError(__('string.delete_user.problem_try_again'));
            //     }
            // }

            $path = URL_STORAGE_IMAGE_FACE . '/' . $user->id . '/';
            system("rm -rf ".escapeshellarg($path));

            // if ($user->delete()) {

            

            // $it = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS);
            // $files = new \RecursiveIteratorIterator($it,
            //             \RecursiveIteratorIterator::CHILD_FIRST);
            // foreach($files as $file) {
            //     if ($file->isDir()){
            //         rmdir($file->getPathname());
            //     } else {
            //         unlink($file->getPathname());
            //     }
            // }
            // rmdir($path);


            if ($user->forceDelete()) {

                // Delete folder in storage

                $message = __('string.delete_user.delete_success');
                if ($user->isAdmin) {
                    $message = __('string.delete_user.delete_admin_success');
                }

                DB::commit();
                return $this->returnSuccess([], $message);
            }

            //There was a problem deleting this user. Please try again
            return $this->returnError(__('string.delete_user.problem_try_again'));
        } catch (\Exception $e) {
			\Log::error('■'.__CLASS__.'|'.__FUNCTION__.'|'.__LINE__.'|'.__FILE__.'|'.$e->getMessage());
            \Log::error($e->getMessage());
            DB::rollBack();
            return $this->returnError(__('string.server.common.error'));
        }
    }

    /**
     * upload face image
     * @param $params
     * @return mixed
     * @throws Throwable
     */

     public function uploadCaptureFace($params)
    {
        DB::beginTransaction();
        try {
            $dataImageSendApi = array();
            foreach ($params['image'] as $key => $image) {
                if (!empty($image)) {
                    $dataImageSendApi[$key] = substr($image, strpos($image, ',') + 1);
                } else {
                    $faceImage = $this->imageFaceCaptureRepository->findUserUpload($params['user_id']);
                    $filename = URL_IMAGE_FACE .'/'. $faceImage->$key;
                    if(Storage::disk('public')->exists($filename)) {
                        $dataImageSendApi[$key] = base64_encode(Storage::disk('public')->get($filename));
                    }
                }
            }

            $dataSenApi = array();
            $dataSenApi['id'] = $params['user_id'];
            $dataSenApi['images'] = $dataImageSendApi;
            $user = $this->userRepository->findUserById($params['user_id']);
            if($user) {
                $dataSenApi['username'] = $user->username;
                $dataSenApi['name'] = $user->name;
                $dataSenApi['pronunciation_ja'] = $user->pronunciation_ja;
            }
            if(array_key_exists('is_edit',$params) && $params['is_edit'] == '2') {
                $responseApi = curlCallApiFaceBank(ForwardController::env('URL_DETECTOR_FACE_IMAGE'), json_encode($dataSenApi));
            }else{
                $responseApi = curlCallApiFaceBank(ForwardController::env('URL_REGISTER_FACE_IMAGE'), json_encode($dataSenApi));
            }
            $json_response = json_decode($responseApi['response'], true);
            if(!is_null($json_response)) {
                if ($responseApi['status'] == 200) {
                    if(array_key_exists('status',$json_response)) {
                        if($json_response['status'] == RESPONSE_OK) {
                            $path = URL_IMAGE_FACE . '/' . $params['user_id'] . '/';
                            if (! Storage::disk('public')->exists($path)) {
                                Storage::disk('public')->makeDirectory($path);
                            }
                            $dataStore = [];
                            foreach ($params['image'] as $key => $image) {
                                if (!empty($image)) {
                                    $data = substr($image, strpos($image, ',') + 1);
//                                    $filename = $params['user_id'] . '_' . FACE_DIRECTION[$key] . IMAGE_FACE_EXTENSION;
                                    $filename = $key . IMAGE_FACE_EXTENSION;
                                    $dataStore[$key] = $params['user_id'] . '/' . $filename;
                                    if (Storage::disk('public')->exists($path . $filename)) {
//                                        Storage::disk('public')->delete($path . $filename);
                                        Storage::disk('public')->move($path . $filename, $path . $filename . '_' . date('YmdHis') . '.delete');
                                    }
                                    Storage::disk('public')->put($path . $filename, base64_decode($data));
                                }
                            }
                            if(array_key_exists('info',$json_response)) {
                                foreach ($json_response['info'] as $key => $value) {
                                    $jsonname = $path . $key . '.json';
                                    if (Storage::disk('public')->exists($jsonname)) {
                                        Storage::disk('public')->move($jsonname,$jsonname . '_' . date('YmdHis') . '.delete');
                                    }
                                    Storage::disk('public')->put($jsonname, json_encode($value));
                                }
                            }
                            if ($this->imageFaceCaptureRepository->uploadImageFace($params['user_id'], $dataStore)) {
                                DB::commit();
                                return $this->return(true,'',$json_response);
                            }
                        }
                    }
                }
                if(array_key_exists('message',$json_response)) {
                    return $this->return(false,$json_response['message'],$json_response);
                }else{
                    return $this->return(false,__('string.capture_face.create_fail'),$json_response);
                }
            }
            return $this->returnError(__('string.capture_face.connect_fail').'<br>'.$responseApi['response']);
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            DB::rollBack();
            return $this->returnError(__('string.capture_face.create_fail').'<br>'.$e->getMessage());
        }

    }

    public function getInfo($user_id) {
        $ret = array();
        foreach(FACE_DIRECTION as $key => $value) {
            $jsonFile = URL_IMAGE_FACE .'/'. $user_id . '/' . $key . '.json';
            if(Storage::disk('public')->exists($jsonFile)) {
                $ret[$key] = json_decode(Storage::disk('public')->get($jsonFile),True);
            }
        }
        return $ret;
    }

    /**
     * Store Checkin History
     *
     * @param   array $attributes
     * @return  mix
     */
    public function checkin(array $attributes)
    {
        DB::beginTransaction();
        try {
//            $user = $this->userRepository->findUserById($attributes['id']);
//
//            if ($user) {
//                $data['user_id'] = $user->id;
				$data['user_id'] = $attributes['id'];
                $data['checkin_at_time'] = $this->makeTimeCheckInApi($attributes['time']);
                $date = new DateTime($data['checkin_at_time']);
                $filename = sprintf(
                    '%s_%s.png',
                    $date->format('YmdHis'),
                    sprintf('%08d', $data['user_id'])
                );

                $data['image'] = $this->saveImageToFolder(
                    $attributes['face_image'],
                    $filename
                );
                $data['in_or_out'] = strtolower($attributes['flag']) == CHECKIN['flag_text_in']
                    ? CHECKIN['flag_in']
                    : CHECKIN['flag_out'];

				$data['flag'] = $attributes['flag'];
				if(array_key_exists('temperature',$attributes)) {
					$data['temperature'] = $attributes['temperature'];
				};
				if(array_key_exists('remote_addr',$attributes)) {
					$data['remote_addr'] = $attributes['remote_addr'];
				};
##K.Nakazaki 2023/06/29 開始
                \Log::error('■'.__CLASS__.'|'.__FUNCTION__.'|'.__LINE__.'|'.__FILE__.'|'.var_export($attributes,True));
                if(array_key_exists('device',$attributes)) {
                    $data['device'] = $attributes['device'];
                };
                \Log::error('■'.__CLASS__.'|'.__FUNCTION__.'|'.__LINE__.'|'.__FILE__.'|'.var_export($data,True));
##K.Nakazaki 2023/06/29 終了
                if ($this->checkinHistoryRepository->createCheckin($data)) {
                    DB::commit();
                    return $this->returnSuccess([], __('string.checkin.create.success'));
                }
//            }
            return $this->returnError(__('string.checkin.create.fail'));
        } catch (\Exception $e) {
            \Log::error("Error Checkin: " . $e->getMessage());
            DB::rollBack();
        }
        return $this->returnError(__('string.checkin.create.fail'));
    }

    /**
     * Get List CheckIn History Of A User
     *
     * @param int|string $user_id
     * @param array $params
     * @return mix
     */
    public function getListCheckInHistory($user_id, array $params = [])
    {
        return $this->returnSuccess(
            $this->checkinHistoryRepository->getListCheckin($user_id, $params)
        );
    }

	public function getUserlist(array $attributes)
	{
		$userlist = [];
		$user = $this->userRepository->model;
		if(array_key_exists('id',$attributes)) {
			$user = $user->where('id',$attributes['id']);
		}
		$user = $user->orderBy('id');
        foreach($user->get() as $value) {
            $rec = array();
            $rec['id'] = $value->id;
            $rec['name'] = $value->name;
            $rec['email'] = $value->email;
            $rec['username'] = $value->username;
            $rec['pronunciation_ja'] = $value->pronunciation_ja;
			if(array_key_exists('id',$attributes)) {
	            $faceImage = $this->imageFaceCaptureRepository->findUserUpload($rec['id']);
	            if($faceImage) {
					$rec['images'] = array();
					foreach(FACE_DIRECTION as $key => $value) {
		                $filename = URL_IMAGE_FACE .'/'. $faceImage->$key;
		                if(Storage::disk('public')->exists($filename)) {
		                    $rec['images'][$key] = base64_encode(Storage::disk('public')->get($filename));
		                }
		            }
				}
			}
            $userlist[] = $rec;
        }
		return $userlist;
	}
//##K.Nakazaki 2023/06/28 開始
    public function getCheckinHistoryList(array $params = [], $paginate = 0)
    {
        return $this->checkinHistoryRepository->getCheckinHistoryList($params,$paginate);
    }
    public function getUser()
    {
        return $this->checkinHistoryRepository->getUser();
    }
    public function getCheckinHistoryImage(array $params = [])
    {
        return $this->checkinHistoryRepository->getCheckinHistoryImage($params);
    }
//##K.Nakazaki 2023/06/28 終了
}
