<?php

namespace App\Http\Controllers\Dealers;

use App\Enum\Status;
use App\Models\Role;
use App\Models\Term;
use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\Dealers\Dealer;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\Dealer\RegisterRequest;

class RegisterController extends Controller
{
    public function index(Request $request)
    {
        $term = Term::wherePosition('register_page')->first();
        return view('auth.dealers.register', compact('term'));
    }

    public function store(RegisterRequest $request)
    {
        try {
            DB::beginTransaction();

            $dealer = Dealer::create([
                'company_name' => $request->input('company_name'),
                'registration_number' => $request->input('registration_number'),
                'tax_identification_number' => $request->input('tax_id'),
            ]);

            $user = $dealer->user()->create([
                'first_name' => $request->input('company_name'),
                'email' => $request->input('company_email'),
                'phone' => $request->input('company_phone'),
                'status' => Status::PENDING,
                'password' => Hash::make($request->input('password')),
            ]);

            $user->settings()->createMany([
                ['key' => 'is_dark_mode', 'value' => false],
                ['key' => 'is_compact_sidebar', 'value' => false],
            ]);

            $user->assignRole(Role::DEALER);

            $dealer->representatives()->create([
                'full_name' => $request->input('rep_name'),
                'nic_number' => $request->input('rep_cnic'),
                'position' => $request->input('rep_position'),
                'contact_phone' => $request->input('rep_contact'),
            ]);

            $dealer->finances()->create([
                'name' => $request->input('bank_name'),
                'account_holder_name' => $request->input('account_holder'),
                'account_number' => $request->input('account_number'),
            ]);

            $dealer->addresses()->create([
                'country' => $request->input('country'),
                'state' => $request->input('state'),
                'city' => $request->input('city'),
                'street' => $request->input('street'),
                'postal_code' => $request->input('postal_code'),
            ]);

            DB::commit();
            return redirect()->route('login')->with('success', 'Dealer registered successfully');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage(), $e->getTrace());
            return $this->sendServerErrorResponse($e);
        }
    }
}
