<?php

namespace Modules\User\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\Response\ResponseService;
use Auth;
use Hash;
use Illuminate\Http\JsonResponse;
use Modules\User\Requests\Api\CheckCodeRequest;
use Modules\User\Requests\Api\LoginRequest;
use Modules\User\Requests\Api\RegisterRequest;
use Modules\User\Requests\Api\ResetPasswordRequest;
use Modules\User\Requests\Api\SendCodeRequest;

use Modules\User\Resources\Api\UserResource;
use Modules\User\Services\UserService;
use Modules\User\Services\VerificationService;
use Modules\User\Services\TaqnyatSmsService;
class AuthController extends Controller
{

    public function __construct(
        private UserService $userService,
        private VerificationService $verificationService,
        private TaqnyatSmsService $taqnyatSmsService,
    ) {
    }

    /**
     * Login.
     *
     * @param LoginRequest $request
     * @return JsonResponse
     */
    public function login(LoginRequest $request): JsonResponse
    {
        $credentials = $request->only('phone', 'password', 'id_number');
        $credentials['rule'] = 4;
        $credentials['trashed'] = true;
        $user = $this->userService->get($credentials);

        if ($user) {
            $passwordTrue = Hash::check($request->password, $user->password);
            if (!$passwordTrue) {
                $response = [
                    'status' => 400,
                    'message' => __('auth.failed'),
                ];
            }
            if ($passwordTrue) {
                if ($user->deleted_at && !($request->activate ?? null)) {
                    $response = [
                        'status' => 200,
                        'message' => __('auth.need_activated'),
                        'data' => ['need_activated' => true]
                    ];
                }
                if ($user->deleted_at && $request->activate) {
                    $this->userService->destroy($user->id);
                    $user = $this->userService->getItem($user->id);
                }
                if (!$user->deleted_at) {
                    Auth::login($user);
                    $apiToken = md5(time() . rand(1000, 1110));
                    $user = $this->userService->update(['api_token' => $apiToken,'device_token'=>$request->device_token??null], auth()->id());
                    $response = [
                        'status' => 200,
                        'message' => '',
                        'data' => ['user' => new UserResource($user), 'api_token' => $apiToken],
                    ];
                }

            }
        } elseif (!$user) {
            $response = [
                'status' => 400,
                'message' => __('auth.failed'),
            ];
        }

        return ResponseService::response($response);
    }
    /**
     * Send Code.
     *
     * @param SendCodeRequest $request
     * @return JsonResponse
     */
    public function sendCode(SendCodeRequest $request): JsonResponse
    {
        $credentials = $request->only('phone', 'op');
        $verification = $this->verificationService->createCode($credentials);
        $message=$verification->code;
        if(currentLanguage()->local=="ar"){
           $message="رمز الأمان الخاص بك هو ".$verification->code."هذا الكود سري وللأستخدم مره واحده";
        }
        if(currentLanguage()->local=="en"){
            $message="Your security code is ".$verification->code." This code is confidential and can only be used once.";
        }
        $response = $this->taqnyatSmsService->sendSms($credentials['phone'], $message);
        // dd($response);

        $response = [
            'status' => 200,
            'message' => '',
            'data' =>
                ['phone' => $verification->phone, 'op' => $verification->op, 'code' => $verification->code]
        ];
        return ResponseService::response($response);
    }
    /**
     * Check Code.
     *
     * @param CheckCodeRequest $request
     * @return JsonResponse
     */
    public function checkCode(CheckCodeRequest $request): JsonResponse
    {
        $credentials = $request->only('phone', 'op', 'code');
        $verification = $this->verificationService->get($credentials);

        $response = [
            'status' => 200,
            'message' => '',
            'data' =>
                ['phone' => $verification->phone, 'op' => $verification->op, 'code' => $verification->code]
        ];
        return ResponseService::response($response);
    }
    /**
     * Reset Password.
     *
     * @param ResetPasswordRequest $request
     * @return JsonResponse
     */
    public function resetPassword(ResetPasswordRequest $request): JsonResponse
    {
        $credentials = $request->only('phone', 'password', 'code');
        $credentials['op'] = "forget_password";
        $verification = $this->verificationService->get($credentials);
        $this->userService->update(['password' => $credentials['password']], $verification->user_id);
        $this->verificationService->destroy($verification->id);
        $response = [
            'status' => 200,
            'message' => '',
            'data' =>
                ['password_changed' => true]
        ];
        return ResponseService::response($response);
    }
    /**
     * Register.
     *
     * @param RegisterRequest $request
     * @return JsonResponse
     */
    public function store(RegisterRequest $request): JsonResponse
    {
        $credentials = $request->only('phone', 'name', 'code', 'last_name', 'email', 'id_number', 'password', 'password_confirmation');
        $apiToken = md5(time() . rand(1000, 1110));
        $credentials['api_token'] = $apiToken;
        $credentials['device_token']=$request->device_token??null;
        $credentials['role'] = 4;
        $user = $this->userService->create($credentials);
        $verification = $this->verificationService->get([
            'phone' => $request->phone,
            'code' => $request->code,
            'op' => 'register'
        ]);
        $this->verificationService->destroy($verification->id);
        Auth::login($user);
        $response = [
            'status' => 200,
            'message' => '',
            'data' => ['user' => new UserResource($user), 'api_token' => $apiToken]
        ];
        return ResponseService::response($response);
    }
}
