<?php

namespace App\Services;

use App\Models\User;
use App\Models\Role;
use App\Models\Registration;
use App\Models\MemberProfile;
use App\Models\LeasingProfile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class RegistrationService
{
    /**
     * Register a new member.
     */
    public function registerMember(array $data)
    {
        return DB::transaction(function () use ($data) {
            $role = Role::where('name', 'member')->first();
            if (!$role) throw new \Exception('Role member tidak ditemukan di sistem. Hubungi administrator.');

            $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'phone' => $data['phone'] ?? null,
                'password' => Hash::make($data['password']),
                'role_id' => $role->id,
                'account_status' => 'pending',
            ]);

            MemberProfile::create([
                'user_id' => $user->id,
                'address' => $data['address'] ?? null,
                'id_card_number' => $data['id_card_number'] ?? null,
            ]);

            Registration::create([
                'user_id' => $user->id,
                'registration_type' => 'member',
                'registration_status' => 'pending',
            ]);

            return $user;
        });
    }

    /**
     * Register a new leasing company.
     */
    public function registerLeasing(array $data)
    {
        return DB::transaction(function () use ($data) {
            $role = Role::where('name', 'leasing')->first();
            if (!$role) throw new \Exception('Role leasing tidak ditemukan di sistem. Hubungi administrator.');

            $user = User::create([
                'name' => $data['owner_name'],
                'email' => $data['email'],
                'phone' => $data['phone'] ?? null,
                'password' => Hash::make($data['password']),
                'role_id' => $role->id,
                'account_status' => 'pending',
            ]);

            LeasingProfile::create([
                'user_id' => $user->id,
                'company_name' => $data['company_name'],
                'address' => $data['address'] ?? null,
            ]);

            Registration::create([
                'user_id' => $user->id,
                'registration_type' => 'leasing',
                'registration_status' => 'pending',
            ]);

            return $user;
        });
    }
}
