<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Http\Requests\AuthRequest;
use App\Models\User;
use App\Models\UserCode;
use App\Traits\BaseApiResponse;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;

class AuthController extends Controller
{
    use BaseApiResponse;

    public function login(AuthRequest $request)
    {
        $user = User::query()
            ->where('mobile', $request->mobile)
            ->firstOr(function () use ($request) {
                return User::create([
                    'name' => 'Law',
                    'mobile' => $request->mobile,
                    'email' => 'law' . $request->mobile . '@law.com',
                    'password' => Hash::make($request->mobile),
                ]);
            });

        $code = random_int(1000, 9999);
        UserCode::create([
            'user_id' => $user->id,
            'code' => $code,
            'expired_at' => Carbon::now()->addMinutes(10),
        ]);

        $url = 'https://api.sms.ir/v1/send/verify';

        $payload = [
            'mobile' => $request->mobile,
            'templateId' => '383927',
            'parameters' => [
                [
                    'name' => 'CODE',
                    'value' => strval($code),
                ],
            ],
        ];

        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Accept' => 'text/plain',
            'x-api-key' => 'VNXiXc1ERkFUwifxfYFzOIOCjNow9E8as1NpUE5EtkDkaWUlmC09nGxJCFX3kSqD',
        ])
            ->post('https://api.sms.ir/v1/send/verify', $payload);

        if ($response->successful()) {
            return $this->success([], 'موفق', 'کد ورود به شماره موبایل شما ارسال شد');
        } else {
            return $this->failed([], 'نا موفق', 'در ارسال کد به شماره شما مشکلی وجود دارد');
        }
    }

    public function verify(Request $request)
    {
        $request->validate([
            'mobile' => 'required',
            'code' => 'required',
        ]);

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

        if (! $user) {
            return response()->json(['error' => 'User not found'], 404);
        }

        $latestCode = UserCode::where('user_id', $user->id)
            ->where('code', $request->code)
            ->latest()
            ->first();

        if (! $latestCode) {
            return $this->failed([], 'کد ورود اشتباه است', 404);
        }

        if ($latestCode->code === $request->code) {
            $token = $user->createToken('mobile')->plainTextToken;

            return $this->success(['token' => $token], 'ورود موفقیت امیز بود');
        } else {
            return $this->failed([], 'کد ورود اشتباه است', 404);
        }
    }
}
