<?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;
use App\Services\EmailService;
use App\Services\SmsService;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use App\Models\Customer;


class CustomerAuthenticationController 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 == 'customer'){
                $token = $user->createToken('codeharry')->plainTextToken;
                return response()->json(['token' => $token, 'message' => 'Login Successfully, redirecting'], 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);
            }
            
            $username = $request->input('username');
            
            // Find the user by phone or email
            $user = User::where('phone', $username)
                ->orWhere('email', $username)
                ->first();
            
            if (!$user) {
                DB::beginTransaction();
                // Create a new user if not found
                $user = User::create([
                    'phone' => filter_var($username, FILTER_VALIDATE_EMAIL) ? null : $username,
                    'email' => filter_var($username, FILTER_VALIDATE_EMAIL) ? $username : null,
                    'role' => 'customer', // Assuming default role as 'customer'
                    'status' => true,
                ]);

                $customer = Customer::create([
                    'user_id' => $user->id,
                ]);
                DB::commit();
            }
            
            // Check the role of the user
            if ($user->role !== 'customer') {
                return response()->json(['message' => 'The given phone/email is not registered as a customer'], 404);
            }
            
            // Generate or reuse OTP
            $otpRecord = Otp::where('username', $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' => $username],
                    ['otp' => $otp, 'expires_at' => $expires_at]
                );
            }
            
            // Send OTP via SMS or email
            $params = [
                'phone' => $user->phone,
                'otp' => $otp,
                'email' => $user->email,
            ];
            $sms = SmsService::loginOtp($params);
            $email = EmailService::loginOtp($params); // Uncomment if email service is used
            
            $message = $isResend ? 'OTP resent successfully.' : 'OTP sent successfully and valid for 10 minutes';
            return response()->json(['message' => $message, 'sms' => $sms]);
        /*} catch (\Exception $e) {
            return response()->json(['message' => '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);
            }
            $is_new = false;

            $user = User::where('phone', $request->username)
            ->orWhere('email', $request->username)
            ->first();
            $token = $user->createToken('auth-token')->plainTextToken;

           if(empty($user->name)){
                $is_new = true;
            }

            $otpRecord->delete();
    
            // You might want to create a token for the authenticated user
            
    
            // Delete OTP record after successful verification
    
            return response()->json(['message' => 'OTP verified successfully, redirecting', 'token' => $token, 'is_new' => $is_new],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']);
    }






    
}
