<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\Admin;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Mail;
use App\Models\PasswordReset;
use Carbon\Carbon;



class AuthController extends Controller
{
    //
    public function register(Request $request) {
        //Validation
        $validator = Validator::make($request->all(), [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
            'c_password' => 'required|same:password',
        ]);

        if($validator->fails()) {
            $response = [
                'success' => false,
                'message' => $validator->errors()
            ];
            return response()->json($response, 400);
        }
//         echo createSlug('admins', $request->first_name);
// exit();
        $input = $request->all();
        $input['first_name'] = $request->first_name;
        $input['last_name'] = $request->last_name;
        $input['email'] = $request->email;
        $input['username'] = $request->username;
        $input['password'] = bcrypt($input['password']);
        $input['status'] = 1;
        $input['slug'] = createSlug('admins', $request->first_name);
        $user = Admin::create($input);
        // print_r($input);
        $success['token'] = $user->createToken('MyApp')->plainTextToken;
        $success['first_name'] = $user->first_name;

        $response = [
            'success' => true,
            'data' => $success,
            'message' => 'User register successfully'
        ];

        return response()->json($response, 200);
    }

    // public function login(Request $request) {
    //     // Validation
    //     $credentials = $request->only('email', 'password');
    
    //     if (Auth::guard('admin')->attempt($request->only('email', 'password'))) {
    //         //$user = Auth::guard('admin')->user();
    //         $user = Admin::where('email', $request->email)->first();
    //         $token = $user->createToken('MyApp')->plainTextToken;
    
    //         $response = [
    //             'success' => true,
    //             'status' => 200,
    //             'token' => $token,
    //             'user' => $user,
    //             'message' => 'User logged in successfully'
    //         ];
    //         return Response(['response' => $response],200);
    //         // return response()->json($response, 200);
    //     } else {
    //         $response = [
    //             'success' => false,
    //             'message' => 'Unauthorized'
    //         ];
    //         return response()->json($response, 401);
    //     }
    // }
    
    public function login(Request $request) {

        if (!empty($request->all())) {
            
            $validator = Validator::make($request->all(), [
                'email' => 'required|email',
                'password' => 'required',

            ]);
            
            $validator->setAttributeNames([
                'email' => 'Email',
                'password' => 'Password',
            ]);

            if ($validator->fails()) {
                return Response(['response' => $validator->errors(), 'status' => 500], 200);
            } else {
                $credentials = $request->only('email', 'password');
            echo Auth::guard('admin')->attempt($request->only('email_address', 'password'));
                if (Auth::guard('admin')->attempt($request->only('email', 'password'))) {
                    //$user = Auth::guard('admin')->user();
                    $user = Admin::where('email', $request->email)->first();
                    $token = $user->createToken('MyApp')->plainTextToken;
            
                    $response = [
                        'success' => true,
                        'token' => $token,
                        'user' => $user,
                        'message' => 'User logged in successfully',
                        'status' => 200
                    ];
                    // return response()->json($response, 200);
                    return Response(['response' => $response]);
                } else {
                    $user = Admin::where('email', $request->email)->first();
            
                    if (!$user) {
                        
                        $response = [
                            'success' => false,
                            'message' => 'Email not registered',
                            'status' => 500
                        ];
                    } else {
                        $response = [
                            'success' => false,
                            'message' => 'Invalid credentials',
                            'status' => 500
                        ];
                    }
                    return Response(['response' => $response]);
                   
                    // return response()->json($response, 401);
                }
            }

        }
    }
    
    //   Forget Password api method 
    public function forgetPassword(Request $request) {
         
        try{
            
            if(empty($request->email)) {
                return Response(['response' => 'Email is required', 'status' => 500], 200);
            }
            $user = Admin::where('email', $request->email)->get();
               

              if(count($user) > 0) {
                  $token = Str::random(60);
                  $domain = URL::to('/');
                  $url = HTTP_PATH_FRONTEND.'/resetpassword/'.$token;

                  $data['url'] = $url;
                  $data['email'] = $request->email;
                  $data['title'] = 'Reset Password';
                  $data['body'] = 'Please click on the link below to reset your password';

                  Mail::send('forgetpassword', ['data' => $data], function($message) use($data) {
                      $message->to($data['email']);
                      $message->subject($data['title']);
                  });


                 $datetime = Carbon::now()->format('Y-m-d H:i:s');
                 
                 $passwordReset = PasswordReset::firstOrNew(
                    ['email' => $request->email]
                );
                
                $passwordReset->email = $request->email;
                $passwordReset->token = $token;
                $passwordReset->created_at = $datetime;
                
                $passwordReset->save();

                // echo "hi";
                 return Response(['response' => 'success', 'message'=> 'We have e-mailed your password reset link!', 'status' => 200], 200);

              }
              else{
                  return Response(['response' => 'Email not registered', 'status' => 500], 200);
              }
           

       

        }
        catch(Exception $e) {
            return Response(['response' => $e->getMessage(), 'status' => 500], 200);
        }
            
    }



    public function resetPassword(Request $request) {


        $validator = Validator::make($request->all(), [
            'token' => 'required',
            'new_password' => 'required|min:8',
            'confirm_password' => 'required | same:new_password'
        ]);

        $validator->setAttributeNames([
            'token' => 'Token',
            'new_password' => 'New Password'
        ]);
    
        if($validator->fails()) {
            return Response(['response' => $validator->errors(), 'status' => 500], 200);
        }


        // echo "Hi";
        // exit();
       
        $resetPassword = PasswordReset::where('token', $request->token)->first();
    
        
        if ($resetPassword) {
            // Find the user by email
            $user = Admin::where('email', $resetPassword->email)->first();
    
            if ($user) {
                // Update the user's password
                $user->password = bcrypt($request->new_password);
                $user->save();
    
                
                // $resetPassword->delete();
                PasswordReset::where('token', $request->token)->delete();
                return Response([
                    'response' => 'success',
                    'msg' => 'Your password has been reset successfully!',
                    'status' => 200
                ], 200);
            } else {
                
                return Response([
                    'success' => false,
                    'message' => 'User not found'
                ], 404);
            }
        } else {
            
            return Response([
                'success' => false,
                'message' => 'Invalid token'
            ], 401);
        }
    }
     
    
}