<?php

namespace Modules\Linksehat\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Models\Person;
use App\Models\OLDLMS\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Laravel\Socialite\Facades\Socialite;
use Modules\Linksehat\Transformers\User\UserProfileResource;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Http;
use Validator;

class AuthController extends Controller
{
    private $url;

    public function __construct() {
        $this->url = $_ENV['LMS_APP_URL'];
    }

    public function login(Request $request)
    {       
        $request->validate([
            // 'email' => 'email',
            'phone_or_email' => 'required',
            // 'phone' => '',
            // 'otp' => 'required_with:phone',
            'password' => 'required',
            // 'otp' => 'required'
        ]);

        // Login hit ke API linksehat, karena encrypt nya pake CI
        $response = Http::post($this->url.'login', [
            'sEmail' => $request->phone_or_email,
            'sPassword' => $request->password,
            'sRemember' => $request->remember
        ]);

        $response = $response->json();
        if ($response['success']){
            $user = User::with('detail')
            ->where('sEmail', $request->phone_or_email)
            ->first();
            return Helper::responseJson(
                data: [
                    'token' => $user->createToken('app')->plainTextToken,
                    'user' => UserProfileResource::make($user),
                ],
                message: 'Selamat Datang'
            );
        } else {
            return response(['message' => 'Email atau Password salah, Silahkan Cek Kembali'], 403);
        };
    }

    public function forgetPassword(Request $request){
        $request->validate([
            'email' => 'required|email',
        ]);

        // Login hit ke API linksehat, karena encrypt nya pake CI
        $response = Http::post($this->url.'forgot_password', [
            'sEmail' => $request->email,
        ]);

        $response = $response->json();
        if ($response['success']){
            return Helper::responseJson(
                data: [],
                message: 'Message has been sent.'
            );
        } else {
            return response(['message' => 'Email atau Password salah, Silahkan Cek Kembali'], 403);
        };
    }

    public function resetPassword(Request $request){
        $request->validate([
            'email' => 'required|email',
            'code' => 'required',
            'password' => 'required',
        ]);

        // Login hit ke API linksehat, karena encrypt nya pake CI
        $response = Http::post($this->url.'reset_password', [
            'sCode' => $request->code,
            'sEmail' => $request->email,
            'sPassword' => $request->password,
        ]);

        $response = $response->json();
        if ($response['success']){
            return Helper::responseJson(
                data: [],
                message: 'Password telah di reset'
            );
        } else {
            return response(['message' => $response['message']], 403);
        };
    }

    public function loginPhone(Request $request)
    {       
        $request->validate([
            'phone_or_email' => 'required',
            'otp' => 'required',
        ]);

        $user = User::with('detail')
            ->where([
                'sPhone' => $request->phone_or_email,
                'sVerificationCode' => $request->otp
            ])
        ->first();

        if ($user){

            $updateVericationCode = User::with('detail')
                ->where([
                    'sPhone' => $request->phone_or_email,
                    'sVerificationCode' => $request->otp
                ])->update([
                    'sVerificationCode' => null,
                ]);
            return Helper::responseJson(
                data: [
                    'token' => $user->createToken('app')->plainTextToken,
                    'user' => UserProfileResource::make($user),
                ],
                message: 'Selamat Datang'
            );
        } else {
            return response(['message' => 'Email atau Password salah, Silahkan Cek Kembali'], 403);
        };
    }

    public function otpRequest(Request $request)
    {

        $user = User::with('detail')
            ->where('sPhone', $request->phone_or_email)
            ->first();
        
        if ($user){
            // Request OTP ke API linksehat
            $response = Http::post($this->url.'generate_code', [
                'sPhone' => $request->phone_or_email
            ]);
    
            $response = $response->json();
    
            return Helper::responseJson(
                data: [
                    'otp' => $response['message'],
                ],
                message: 'Kode OTP'
            );
        } else {
            return Helper::responseJson(
                data: [
                    'otp' => null,
                ],
                message: 'Nomor tidak ditemukan'
            );
        }

        

    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|unique:users,email',
            'password' => [
                'required',
                'confirmed',
                'min:8',
                'regex:/.*[0-9].*/',
                'regex:/.*[a-z].*/',
                'regex:/.*[A-Z].*/',
            ]
        ], [
            'password.regex' => "Password harus minimal 8 karakter, kombinasi huruf besar kecil dan angka"
        ])->validate();

        try {
            User::create([
                'email' => $request->email,
                'password' => Hash::make($request->password),
            ]);

            return Helper::responseJson(statusCode: Response::HTTP_CREATED, message: 'Akun berhasil dibuat, silahkan cek E-mail untuk konfirmasi');
        } catch (\Exception $e) {
            return Helper::responseJson(['error_message' => $e->getMessage()], Response::HTTP_FORBIDDEN, 'Terjadi masalah ketika mendaftar');
        }
    }

    public function logout(Request $request)
    {
        $token = $request->bearerToken();
        Auth::user()->tokens()->where('id', $token)->delete();

        return Helper::responseJson(message: 'Behasil Logout.');
    }

   
    public function mockOtp(Request $request)
    {
        $request->validate([
            'phone_or_email' => 'required'
        ]);

        $user = User::query()->where((filter_var($request->phone_or_email, FILTER_VALIDATE_EMAIL) ? 'email' : 'phone'), $request->phone_or_email)->firstOrFail();

        return Helper::responseJson(data: [
            'otp' => $user->otp,
            'otp_valid_until' => $user->otp_created_at ? $user->otp_created_at->addMinutes(config('linksehat.otp_valid_minutes')) : null
        ], message: 'OTP Anda');
    }

    public function redirectSocialLogin($provider)
    {
        return Socialite::driver($provider)->redirect();
    }

    public function handleSocialLoginCallback($provider)
    {
        $providerUser = Socialite::driver($provider)->stateless()->user();
        $user = User::query()->firstWhere('email', $providerUser->email);

        if (!$user) {
            $user = User::query()->create([
                'email' => $providerUser->email,
            ]);

            $person = Person::query()->create([
                'owner_user_id' => $user->id,
                'name' => $providerUser->name,
                'email' => $providerUser->email,
                'created_by' => $user->id,
            ]);

            User::query()->find($user->id)->update([
                'person_id' => $person->id
            ]);
        }

        return Helper::responseJson(data: [
            'user' => UserProfileResource::make($user),
            'token' => $user->createToken('app')->plainTextToken
        ], message: 'Selamat Datang');
    }
}
