<?php

namespace App\Http\Controllers;

use App\Models\Daftar;
use App\Models\Perusahaan;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class SignupController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->validate([
            'company_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        // Create user and signup record
        DB::beginTransaction();
        try {
            $user = User::create([
                'name' => $data['company_name'],
                'email' => $data['email'],
                'username' => $data['email'],
                'password' => Hash::make($data['password']),
            ]);

            // Ensure 'perusahaan' role exists, then assign it
            if (!\Spatie\Permission\Models\Role::where('name', 'perusahaan')->exists()) {
                \Spatie\Permission\Models\Role::create(['name' => 'perusahaan']);
            }
            $user->assignRole('perusahaan');

            // Create Daftar record (Status Active by default)
            $daftar = Daftar::create([
                'NamaPerusahaan' => $data['company_name'],
                'Email' => $data['email'],
                'Password' => Hash::make($data['password']),
                'Status' => 'Active',
            ]);

            // Ensure a Perusahaan exists and attach user via pivot
            $perusahaan = Perusahaan::firstOrCreate(
                ['NamaPerusahaan' => $data['company_name']],
                ['Alamat' => null]
            );

            // Attach user to perusahaan via pivot (avoid duplicates)
            $user->perusahaans()->syncWithoutDetaching([$perusahaan->PerusahaanID]);

            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            report($e);
            return back()->withErrors(['error' => 'Registration failed.']);
        }

    // Redirect to login page; user already has 'perusahaan' role and is attached to perusahaan
    return redirect()->route('login.index')->with('status', 'Akun berhasil dibuat dan aktif. Silakan masuk.');
    }
}
