<?php

namespace App\Http\Controllers\Api\v1;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Validator;
use App\Models\Admin\User;
use App\Models\Admin\Country;
use App\Models\Admin\PasswordReset;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use App\Models\Admin\City;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;


class AuthenticationController extends Controller
{
    public function country(Request $request){
        return response()->json(Country::orderBy('name','asc')->get());
    }
    public function cities(Request $request){
        return response()->json(City::where('country_id',$request->country_id)->orderBy('name','asc')->get());
    }

    public function register(Request $request){
        // Doğrulama kurallarını tanımla
        $validator = Validator::make($request->all(), [
            'name'             => 'required|max:255',
            'company_name'     => 'required|max:255',
            'address'          => 'nullable|max:500',
            'postal_code'      => 'nullable|max:20',
            'country'          => 'nullable|integer',
            'city'             => 'nullable|integer',
            'phone_number'     => 'required|',
            'website'          => 'nullable|url',
            'email'            => 'required|email|max:255|unique:users,email',
            'password'         => 'required|min:8|confirmed',
            'app_language'     => 'nullable',
            'terms_accepted'   => 'required|in:true',
        ],[
            'name.required'           => get_language_variable('validation.name.error'),
            'name.max'                => get_language_variable('validation.name.max'),
            'address.max'             => get_language_variable('validation.address.max'),
            'company_name.required'   => get_language_variable('validation.company_name.error'),
            'company_name.max'        => get_language_variable('validation.company_name.max'),
            'country.required'        => get_language_variable('validation.country.error'),
            'country.integer'        => get_language_variable('validation.country.error'),
            'city.required'           => get_language_variable('validation.city.error'),
            'city.integer'           => get_language_variable('validation.city.error'),
            'phone_number.required'   => get_language_variable('validation.phone_number.error'),
            'website.url'             => get_language_variable('validation.website.error'),
            'email.required'          => get_language_variable('validation.email.error'),
            'email.unique'            => get_language_variable('validation.email.unique'),
            'email.email'             => get_language_variable('validation.email.type'),
            'email.max'               => get_language_variable('validation.email.type'),
            'password.required'       => get_language_variable('validation.password.error'),
            'password.min'            => get_language_variable('validation.password.error.min'),
            'password.confirmed'      => get_language_variable('validation.password.confirmed'),
            'terms_accepted.required' => get_language_variable('validation.terms_accepted.error'),
            'terms_accepted.in'       => get_language_variable('validation.terms_accepted.error'),
            'postal_code.max'         => get_language_variable('validation.postal_code.max'),

        ]);

        // Doğrulamanın geçip geçmediğini kontrol et
        if ($validator->passes()) {
            $user = new User();
            $user->name = $request->name;
            $user->company_name = $request->company_name;
            $user->address = $request->address;
            $user->postal_code = $request->postal_code;
            $user->country_id = $request->country;
            $user->city_id = $request->city;
            $user->phone = $request->phone_number;
            $user->website = $request->website;
            $user->email = $request->email;
            $user->password = Hash::make($request->password);
            $user->email = $request->email;
            if($request->notification_confirmation){
                $user->notification_confirmation = $request->notification_confirmation;
            }
            $user->assignRole('user');
            $user->save();
            $token = $user->createToken('api_token')->plainTextToken;

            activity()
            ->performedOn($user)
            ->log('Üye Oldu!');

            $user->city_name = City::find($user->city_id)->name ?? null;
            $user->country_name = Country::find($user->country_id)->name ?? null;

            return response()->json(['message' => get_language_variable('success_message') , 'user' => $user, 'token' => $token]);
        } else {
            $errors = $validator->errors()->toArray();

            $customErrors = [];

            // "password" için hata mesajlarını ayır
            if (isset($errors['password'])) {
                foreach ($errors['password'] as $errorKey => $error) {
                    if ($error === get_language_variable('validation.password.confirmed')) {
                        $customErrors['password_confirmation'][] = $error;
                    } else {
                        $customErrors['password'][] = $error;
                    }
                }
            }

            // Diğer hata mesajlarını da ekle
            foreach ($errors as $key => $messages) {
                if ($key !== 'password') {
                    $customErrors[$key] = $messages;
                }
            }
            return response()->json([
                'message' => 'Doğrulama hatası.',
                'errors' => $customErrors
            ], 422);
        }
    }

    public function login(Request $request){
       // Doğrulama kurallarını tanımla
        $validator = Validator::make($request->all(), [
            'email'            => 'required|email|max:255',
            'password'         => 'required',
        ],[
            'email.required'          => get_language_variable('validation.email.error'),
            'email.email'             => get_language_variable('validation.email.type'),
            'email.max'               => get_language_variable('validation.email.type'),
            'password.required'       => get_language_variable('validation.password.error'),
        ]);

        // Doğrulamanın geçip geçmediğini kontrol et
        if ($validator->passes()) {

            $user = User::where('email', $request->email)->first();
            if ($user && Hash::check($request->password, $user->password)) {

                $token = $user->createToken('api_token')->plainTextToken;

                    activity()
                    ->performedOn($user)
                    ->log('Üye Mobil Uygulamaya Giriş Yaptı!');

                    $user->city_name = City::find($user->city_id)->name ?? null;
                    $user->country_name = Country::find($user->country_id)->name ?? null;

                    return response()->json(['message' => get_language_variable('success_message_login') , 'user' => $user, 'token' => $token]);


            } else {

                return response()->json(['message' => get_language_variable('error_message_login')], 401);

            }
        } else {
            return response()->json([
                'message' => 'Doğrulama hatası.',
                'errors' => $validator->errors()
            ], 422);
        }
    }

    public function forgot_password(Request $request){
        $validator = Validator::make($request->all(), [
            'email'            => 'required|email|max:255',
        ],[
            
            'email.required'          => get_language_variable('validation.email.error'),
            'email.email'             => get_language_variable('validation.email.type'),
            'email.max'               => get_language_variable('validation.email.type'),
        ]);

        // Doğrulamanın geçip geçmediğini kontrol et
        if ($validator->passes()) {
            $user = User::where('email',$request->email)->first();
            if(!empty($user)){
                $token = rand(100000, 999999);


                // PasswordReset::updateOrCreate(
                //     ['email' => $request->email],
                //     ['token' => Hash::make($token)],
                //     ['created_at' => now()]
                // );
                PasswordReset::updateOrCreate(
                    ['email' => $request->email],
                    [
                        'token' => Hash::make($token),
                        'created_at' => now()
                    ]
                );

                Mail::raw("Şifre sıfırlama kodunuz: $token", function ($message) use ($request) {
                    $message->subject('Dikkan Şifre Sıfırlama')
                        ->from('nr@incefikirler.com', 'Dikkan Şifre Sıfırlama')
                        ->to($request->email);
                });
                
                activity()
                ->performedOn($user)
                ->log('Şifre Sıfırlama Kodu Gönderdi :'.$token);
                
                return response()->json(['message' => get_language_variable('forgot_password_success')]);
            }else{
                return response()->json([
                    'message' => 'Doğrulama hatası.',
                    'errors' => [
                        'email' => [
                            get_language_variable('validation.email.type')
                        ],
                    ]
                ], 422);
            }
        }else{
            return response()->json([
                'message' => 'Doğrulama hatası.',
                'errors' => $validator->errors()
            ], 422);
        }
        
    }

    public function verify_reset_code(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'email' => 'required|email|exists:users,email',
            'token' => 'required',
        ],[
            
            'email.required'          => get_language_variable('validation.email.error'),
            'email.email'             => get_language_variable('validation.email.type'),
            'email.max'               => get_language_variable('validation.email.type'),
            'token.required'          => get_language_variable('validation.token.error'),
        ]);
        
        if ($validator->passes()) {
            $resetData = PasswordReset::where('email', $request->email)->first();

            if (!$resetData || !Hash::check($request->token, $resetData->token)) {
                return response()->json(['message' => get_language_variable('forgot_password_code_error_message')], 401);
            }
            $user = User::where('email',$request->email)->first();
            activity()
                ->performedOn($user)
                ->log('Şifre Sıfırlama Kodu Doğrulandı :'.$request->token);
    
            return response()->json(['message' => get_language_variable('forgot_password_code_success_message')]);
        }else{
            return response()->json([
                'message' => 'Doğrulama hatası.',
                'errors' => $validator->errors()
            ], 422);
        }
        
    }

    public function change_password(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email'    => 'required|email|exists:users,email',
            'token' => 'required',
            'password' => 'required|min:8|confirmed',
        ],[
            'email.required'          => get_language_variable('validation.email.error'),
            'email.email'             => get_language_variable('validation.email.type'),
            'email.max'               => get_language_variable('validation.email.type'),
            'email.exists'            => get_language_variable('validation.email.type'),
            'password.required'       => get_language_variable('validation.password.error'),
            'password.min'            => get_language_variable('validation.password.error.min'),
            'password.confirmed'      => get_language_variable('validation.password.confirmed'),
            'token.required'          => get_language_variable('validation.token.error'),

        ]);

        if ($validator->passes()) {
            $user = User::where('email', $request->email)->first();

            if (!$user) {
                return response()->json(['message' => get_language_variable('user_not_found')], 404);
            }

            $resetData = PasswordReset::where('email', $request->email)->first();

            if (!$resetData || !Hash::check($request->token, $resetData->token)) {
                return response()->json(['message' => get_language_variable('forgot_password_code_error_message')], 401);
            }

            $user->password = Hash::make($request->password);
            $user->save();

            PasswordReset::where('email', $request->email)->delete();

            activity()
                ->performedOn($user)
                ->log('Şifremi Unuttum Tamamlandı Şifre değişti');

            return response()->json(['message' => get_language_variable('change_password_success')]);

        }else{
            $errors = $validator->errors()->toArray();

            $customErrors = [];

            // "password" için hata mesajlarını ayır
            if (isset($errors['password'])) {
                foreach ($errors['password'] as $errorKey => $error) {
                    if ($error === get_language_variable('validation.password.confirmed')) {
                        $customErrors['password_confirmation'][] = $error;
                    } else {
                        $customErrors['password'][] = $error;
                    }
                }
            }

            // Diğer hata mesajlarını da ekle
            foreach ($errors as $key => $messages) {
                if ($key !== 'password') {
                    $customErrors[$key] = $messages;
                }
            }
            return response()->json([
                'message' => 'Doğrulama hatası.',
                'errors' => $customErrors
            ], 422);
            // return response()->json([
            //     'message' => 'Doğrulama hatası.',
            //     'errors' => $validator->errors()
            // ], 422);
        }
    }

    public function user(Request $request){
        if(!empty($request->type) && $request->type == 1){
            return response()->json($request->user->admin_approval);
        } else {
            $user = $request->user;
            $user->city_name = City::find($user->city_id)->name ?? null;
            $user->country_name = Country::find($user->country_id)->name ?? null;
            return response()->json($user);
        }
    }

    public function user_update(Request $request){
        $validator = Validator::make($request->all(), [
            'name'             => 'nullable|max:255',
            'company_name'     => 'nullable|max:255',
            'address'          => 'nullable|max:500',
            'postal_code'      => 'nullable|max:20',
            'country'          => 'nullable|integer',
            'city'             => 'nullable|integer',
            'phone_number'     => 'nullable|',
            'website'          => 'nullable|url',
        ],[
            'name.required'           => get_language_variable('validation.name.error'),
            'name.max'                => get_language_variable('validation.name.max'), 
            'company_name.required'   => get_language_variable('validation.company_name.error'),
            'company_name.max'        => get_language_variable('validation.company_name.max'),
            'address.max'             => get_language_variable('validation.address.max'),
            'postal_code.max'         => get_language_variable('validation.postal_code.max'),
            'country.required'        => get_language_variable('validation.country.error'),
            'country.integer'        => get_language_variable('validation.country.error'),
            'city.required'           => get_language_variable('validation.city.error'),
            'city.integer'           => get_language_variable('validation.city.error'),
            'phone_number.required'   => get_language_variable('validation.phone_number.error'),
            'website.url'             => get_language_variable('validation.website.error'),
        ]);
        if ($validator->passes()) {
            $user_update = User::find($request->user->id);
            if(!empty($request->name)){
                $user_update->name = $request->name;
            }
            if(!empty($request->company_name)){
                $user_update->company_name = $request->company_name;
            }
            if(!empty($request->country)){
                $user_update->country_id = $request->country;
            }
            if(!empty($request->city)){
                $user_update->city_id = $request->city;
            }
            if(!empty($request->phone_number)){
                $user_update->phone = $request->phone_number;
            }
            if(!empty($request->website)){
                $user_update->website = $request->website;
            }
            if(!empty($request->address)){
                $user_update->address = $request->address;
            }
            if(!empty($request->postal_code)){
                $user_update->postal_code = $request->postal_code;
            }
            $user_update->save();

            activity()
                ->performedOn($user_update)
                ->log('Kullanıcı Bilgilerini Güncelledi.');

                $user_update->city_name = City::find($user_update->city_id)->name ?? null;
                $user_update->country_name = Country::find($user_update->country_id)->name ?? null;

            return response()->json(['message' => get_language_variable('success_message') , 'user' => $user_update]);
        }else{
            return response()->json([
                'message' => 'Doğrulama hatası.',
                'errors' => $validator->errors()
            ], 422);
        }
    }

    public function user_password_change(Request $request){
        $validator = Validator::make($request->all(), [
            'old_password'    => 'required',
            'password' => 'required|min:8|confirmed',
        ],[
            'old_password.required'       => get_language_variable('validation.old_password.error'),
            'password.required'       => get_language_variable('validation.password.error'),
            'password.min'            => get_language_variable('validation.password.error.min'),
            'password.confirmed'      => get_language_variable('validation.password.confirmed'),
        ]); 
        if ($validator->passes()) {
            $user_update = User::find($request->user->id);
            if (Hash::check($request->old_password, $user_update->password)) {

                $user_update->password = Hash::make($request->password);
                $user_update->save();

                return response()->json(['message' => get_language_variable('success_message')]);

                activity()
                ->performedOn($user_update)
                ->log('Kullanıcı Şifresini Güncelledi.');
            }else{
                return response()->json([
                    'message' => 'Doğrulama hatası.',
                    'errors' => [
                        'old_password' => [
                            get_language_variable('validation.old_password.error')
                        ]
                    ]
                ], 422);
            }
        }else{
            $errors = $validator->errors()->toArray();

            $customErrors = [];

            // "password" için hata mesajlarını ayır
            if (isset($errors['password'])) {
                foreach ($errors['password'] as $errorKey => $error) {
                    if ($error === get_language_variable('validation.password.confirmed')) {
                        $customErrors['password_confirmation'][] = $error;
                    } else {
                        $customErrors['password'][] = $error;
                    }
                }
            }

            // Diğer hata mesajlarını da ekle
            foreach ($errors as $key => $messages) {
                if ($key !== 'password') {
                    $customErrors[$key] = $messages;
                }
            }
            return response()->json([
                'message' => 'Doğrulama hatası.',
                'errors' => $customErrors
            ], 422);
        }
    }

    public function notification_change(Request $request){


        $user_update = User::find($request->user->id);

        if($user_update->notification_confirmation){
            $user_update->notification_confirmation = 0;
        }else{
            $user_update->notification_confirmation = 1;
        }

        $user_update->save();

        activity()
                ->performedOn($user_update)
                ->log('Kullanıcı Bildirim Ayarını Güncelledi.');
        return response()->json(['message' => get_language_variable('success_message'),'notification_confirmation' => $user_update->notification_confirmation]);

    }
    

}
