<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Otp;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class ManagerAuthenticationController extends Controller
{

    public function emailLogin(Request $request){
        //try {
            $user = User::where('phone', $request->input('username'))
            ->orWhere('email', $request->input('username'))
            ->first();

            if (!$user || !Hash::check($request->password, $user->password)) {
                return response()->json(['message' => 'The provided credentials are incorrect.'], 401);
            }

            if($user->role == 'manager'){
                $token = $user->createToken('codeharry')->plainTextToken;
                $user->load('manager.roleData');
                return response()->json(['token' => $token, 'message' => 'Login Successfully, redirecting', 'permissions' => $user->roleData->permission], 200);
            }else{
                return response()->json(['success' => false, 'message' => 'The provided credentials are incorrect.'], 401);
            }
           
        /*} catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], $e->getCode());
        }*/

    }

    public function otpSend(Request $request){
        try {
            $validator = Validator::make($request->all(), [
                'username' => 'required',
            ]);
    
            if ($validator->fails()) {
                return response()->json(['message' => $validator->errors()], 400);
            }
    
            $user = User::where('phone', $request->input('username'))
                ->orWhere('email', $request->input('username'))
                ->first();
                
            if (!$user) {
                return response()->json(['message' => 'Given phone/email is not registered'], 404);
            } else {
                $otpRecord = Otp::where('username', $request->username)->first();
                $isResend = false;
                if ($otpRecord && Carbon::now()->lt(Carbon::parse($otpRecord->expires_at))) {
                    // Resend existing OTP if it's still valid
                    $otp = $otpRecord->otp;
                    $isResend = true;
                } else {
                    // Create a new OTP if the existing one is expired or doesn't exist
                    $otp = rand(100000, 999999);
                    $expires_at = Carbon::now()->addMinutes(30);
                    Otp::updateOrCreate(
                        ['username' => $request->username],
                        ['otp' => $otp, 'expires_at' => $expires_at]
                    );
                }
    
                $message = $isResend ? 'OTP resent successfully.' : 'OTP sent successfully and valid for 30 minutes';
                return response()->json(['message' => $message, 'otp' => $otp]);
            }
        } catch (\Exception $e) {
            return response()->json(['error' => 'Something went wrong', 'message' => $e->getMessage()], 500);
        }
    }

    public function verifyOtp(Request $request){
        try{
            $validator = Validator::make($request->all(), [
                'username' => 'required',
                'otp' => 'required|digits:6',
            ]);
    
            if ($validator->fails()) {
                return response()->json(['error' => $validator->errors()], 400);
            }
    
            $otpRecord = Otp::where('username', $request->username)
                ->where('otp', $request->otp)
                ->where('expires_at', '>', Carbon::now())
                ->orderBy('created_at', 'desc')
                ->first();
    
            if (!$otpRecord) {
                return response()->json(['message' => 'Invalid OTP or OTP has expired'], 401);
            }

            $user = User::where('phone', $request->username)
            ->orWhere('email', $request->username)
            ->first();
            $otpRecord->delete();

            // You might want to create a token for the authenticated user
            $token = $user->createToken('auth-token')->plainTextToken;
            $user->load('manager.roleData');
    
            // Delete OTP record after successful verification
            
    
            return response()->json(['token' => $token, 'message' => 'OTP verified successfully, redirecting', 'permissions' => $user->roleData->permission],200);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], $e->getCode());
        }
    }



    public function logout(Request $request)
    {
        // Revoke the token that was used to authenticate the current request
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message' => 'Successfully logged out, redirecting']);
    }






    
}
