<?php

namespace App\Http\Controllers;

use App\Exceptions\BalaghatException;
use App\Http\Traits\Api_Trait;
use App\Models\Employee;
use App\Models\User;
use App\Services\smsService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    use Api_Trait;
    public function __construct(private readonly smsService $smsService) {}


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

        $employee = Employee::where('email', $request->email)->first();

        if (!$employee || !Hash::check($request->password, $employee->password)) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }

        $token = $employee->createToken('employee-token')->plainTextToken;

        $data = [
            'token' => $token,
            'employee' => $employee,
        ];
        return $this->returnData($data, __('messages.login_success'));
    }
    public function sendOtp(Request $request)
    {
        $data = $request->validate([
            'national_id' => 'required',
            'phone' => 'required',
        ]);
        $user = User::where('national_id', $data['national_id'])->first();
        if ($user && $user->phone != $data['phone']) {
            return $this->returnInvalidData(['phone' => __('messages.phone_not_match')]);
        }
        if (!$user) {
            $user = User::firstOrCreate([
                'national_id' => $data['national_id'],
                'phone' => $data['phone'],
            ]);
        }

        $otp = rand(1000, 9999);
        $message = "Your OTP code is: $otp. Please do not share it with anyone.";
        $this->smsService->sendSms($user->phone, $message);

        $user->otp = $otp;
        $user->otp_expires_at = now()->addMinutes(10);
        $user->save();
        return $this->returnSuccessMessage(__('messages.otp_sent'));
    }

    public function verifyOtp(Request $request)
    {
        $data = $request->validate([
            'phone' => 'required',
            'otp' => 'required',
        ]);

        $user = User::where('phone', $request->phone)
            ->where('otp', $request->otp)
            ->where('otp_expires_at', '>', Carbon::now())
            ->first();

        if (!$user) {
            return $this->returnErrorNotFound(__('messages.otp_invalid'));
        }

        // Clear OTP after successful verification
        $user->update([
            'otp' => null,
            'otp_expires_at' => null,
        ]);

        // Generate Sanctum token
        $token = $user->createToken('api-token')->plainTextToken;
        $data = [
            'token' => $token,
            'user' => $user,
        ];
         return $this->returnData($data, __('messages.otp_verified'));
    }
}
