<?php

namespace App\Http\Controllers\Api\V1\Entrepreneur;

use App\Http\Controllers\Controller;
use App\Models\Auth\Verification;
use App\Models\Ecommerce\Channel\Channel;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class EntrepreneurAuthController extends Controller
{
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'first_name' => ['required', 'string'],
            'phone_number' => ['required', 'integer', 'between:61000000,71999999', 'unique:users,phone_number'],
            'email' => ['required', 'email', 'unique:users,email'],
            'password' => ['required'],
            'region' => ['required', 'string', 'in:mr,ag,ah,dz,lb,bn'],
            'patent_data' => ['nullable'],
        ]);

        if ($validator->fails()) {
            return response()->rest($validator->messages()->get('*'), 400, 'Wrong credentials');
        }

        DB::transaction(function () use ($request) {
            $user = User::create([
                'first_name' => $request->first_name,
                'last_name' => '       ',
                'email' => $request->email,
                'password' => bcrypt($request->password),
                'phone_number' => $request->phone_number,
            ]);

            $user->documents()->create([
                'patent_data' => str_replace('public/', '', $request->file('patent_data')?->store('public/entrepreneur/patent_data') ?? 'public/'),
            ]);

            sendSMSVerification($request->phone_number);

            // Verification::updateOrCreate(['username' => $request->email, 'code' => 12345]);
        });

        return response()->rest();
    }

    public function verifyPhoneNumber(Request $request)
    {
        $validator = Validator::make($request->all(), ['phone_number' => 'required|integer|between:61000000,65999999', 'code' => 'required|string']);

        if ($validator->fails()) {
            return response()->rest($validator->messages()->get('*'), 400, 'Wrong credentials');
        }

        $verification = Verification::where('username', $request->phone_number)->where('code', $request->code)->first();

        if (! $verification) {
            return response()->rest([], 400, 'Wrong credentials');
        }

        User::where('phone_number', $request->phone_number)->update(['phone_number_verified_at' => now()]);

        return response()->rest();
    }

    public function verifyEmail(Request $request)
    {
        // email should be validated for deleted_at to
        $validator = Validator::make($request->all(), ['email' => ['required', 'string', 'email', 'exists:users,email'], 'code' => ['required', 'string']]);

        if ($validator->fails()) {
            return response()->rest($validator->messages()->get('*'), 400, 'Wrong credentials');
        }

        $verfication = Verification::where('username', $request->email)->where('code', $request->code)->first();

        if (! $verfication) {
            return response()->rest([], 400, 'Wrong credentials');
        }

        $user = User::where('email', $request->email)->first();
        $user->email_verified_at = now();
        $user->save();

        event(new Verified($user));

        return response()->rest();
    }

    public function finalize(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => ['required', 'string', 'email', 'exists:users,email'],
            'password' => ['required', 'string'],
        ]);

        if ($validator->fails()) {
            return response()->rest($validator->messages()->get('*'), 400, 'Wrong credentials');
        }

        if (! auth()->attempt(['email' => $request->email, 'password' => $request->password])) {
            return response()->rest([], 400, 'Wrong credentials');
        }

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

        if (! $user || ! Hash::check($request->password, $user->password)) {
            return response()->rest([], 400, 'Failed');
        }

        if (! $user->hasRole('vendor')) {
            $user->assignRole('vendor');

            // User
            $name = $user->first_name;

            $channel = Channel::create([
                'name' => $name,
                'slug' => Str::slug($name).'_'.random_int(10000, 9999999),
                'description' => '',
                'timezone' => 'asia/ashgabat',
                'url' => url('/'),
                'is_default' => true,
                'channelables_type' => 'App\Models\User',
                'channelables_id' => $user->id,
                'is_visible' => true,
            ]);

            $channel->inventories()->create([
                'name' => $name,
                'code' => Str::slug($name).'_'.random_int(10000, 9999999),
                'region' => 'ag',
                'shareable' => false,
                'is_default' => true,
            ]);
        }

        $bearerToken = $user->createToken(bin2hex(random_bytes(20)))->plainTextToken;

        return response()->rest($bearerToken, 201);
    }

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), ['email' => 'required|string|email', 'password' => 'required|string']);

        if ($validator->fails()) {
            return response()->rest($validator->messages()->get('*'), 400, 'Absolutely wrong credentials.');
        }

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

        if (! $user || ! Hash::check($request->password, $user->password)) {
            return response()->rest([], 400, 'Failed');
        }

        $bearerToken = $user->createToken(bin2hex(random_bytes(20)))->plainTextToken;

        return response()->rest($bearerToken, 201);
    }
}
