<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Traits\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    use ApiResponse;

    public function login(Request $request): JsonResponse
    {
        $request->validate([
            'phone' => ['required', 'string', 'exists:users,phone'],
        ]);

        $user = User::where('phone', $request->phone)
            ->where('status', 1)
            ->first();

        if (!$user) {
            return $this->error('User not found.', 404);
        }

        $otp = rand(1000, 9999);
        $user->update([
            'otp' => $otp,
            'otp_expires_at' => now()->addMinutes(10),
        ]);

        //            $apiResult = $this->send_otp($user->phone, $otp);
        //
        //            if (!$apiResult['success']) {
        //                return $this->error($apiResult['message'], 500);
        //            }

        return $this->success('OTP sent successfully.', [
            'company_name' => $user->account?->name,
            'otp' => $otp,
        ]);
    }

    public function verify(Request $request): JsonResponse
    {
        $request->validate([
            'phone' => ['required', 'string'],
            'otp' => ['required', 'string'],
        ]);

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

        if (!$user) {
            return $this->error('Invalid OTP.', 422);
        }

        if ($user->otp_expires_at && now()->greaterThan($user->otp_expires_at)) {
            return $this->error('OTP has expired.', 422);
        }

        $user->update(['otp' => null, 'otp_expires_at' => null]);

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

        return $this->success('Login successful.', $token);
    }

    private function send_otp(mixed $phone, int $otp): array
    {
        $sms = config('services.sms');
        $message = "Dear User, {$otp} is your one-time OTP, Bluewaves Media";

        $api_params = [
            'username' => $sms['username'],
            'password' => $sms['password'],
            'type' => $sms['type'],
            'sender' => $sms['sender'],
            'mobile' => $phone,
            'message' => $message,
            'entityId' => $sms['entity_id'],
            'templateId' => $sms['template_id'],
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $sms['url']);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            $error_msg = curl_error($ch);
            curl_close($ch);
            return ['success' => false, 'message' => $error_msg];
        }

        curl_close($ch);

        if (str_contains($response, "SUBMIT_SUCCESS")) {
            return ['success' => true];
        }

        return ['success' => false, 'message' => $response];
    }

    public function logout(Request $request): JsonResponse
    {
        $request->user()->currentAccessToken()->delete();

        return $this->success('Logged out successfully');
    }
}
