<?php
// app/Http/Controllers/Auth/RegisteredUserController.php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserAlamat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create()
    {
        // Ambil semua provinsi dari package laravolt/indonesia
        $provinces = \Laravolt\Indonesia\Models\Province::orderBy('name')->get();

        return view('auth.register', compact('provinces'));
    }

    /**
     * Handle an incoming registration request.
     */
    public function store(Request $request)
    {
        // Rules dasar untuk semua role
        $rules = [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'no_hp' => 'required|string|max:20',
            'password' => 'required|min:3',
            'role' => 'required|in:admin,penjual,user',
        ];

        // Jika role adalah 'user', maka alamat wajib diisi
        if ($request->role === 'user') {
            $rules['province_code'] = 'required';
            $rules['city_code'] = 'required';
            $rules['district_code'] = 'required';
            $rules['village_code'] = 'required';
            $rules['alamat_lengkap'] = 'required';
            $rules['kode_pos'] = 'nullable|max:10';
        } else {
            // Untuk admin/penjual, alamat tidak wajib (boleh null)
            $rules['province_code'] = 'nullable';
            $rules['city_code'] = 'nullable';
            $rules['district_code'] = 'nullable';
            $rules['village_code'] = 'nullable';
            $rules['alamat_lengkap'] = 'nullable';
            $rules['kode_pos'] = 'nullable|max:10';
        }

        $request->validate($rules);

        DB::beginTransaction();

        try {
            // ================= USER =================
            // HAPUS 'email_verified_at' dari sini
            $userData = [
                'name' => $request->name,
                'email' => $request->email,
                'no_hp' => $request->no_hp,
                'password' => Hash::make($request->password),
                'role' => $request->role,
                // 'email_verified_at' => now(), // HAPUS BARIS INI
            ];
            
            $user = User::create($userData);

            $user->refresh();

            // ================= ALAMAT (Hanya untuk role 'user') =================
            if ($request->role === 'user') {
                // Validasi wilayah hanya jika diisi
                $province = \Laravolt\Indonesia\Models\Province::find($request->province_code);
                $city = \Laravolt\Indonesia\Models\City::find($request->city_code);
                $district = \Laravolt\Indonesia\Models\District::find($request->district_code);
                $village = \Laravolt\Indonesia\Models\Village::find($request->village_code);

                $user->alamat()->create([
                    'province_code'  => $request->province_code,
                    'city_code'      => $request->city_code,
                    'district_code'  => $request->district_code,
                    'village_code'   => $request->village_code,
                    'nama_penerima'  => $request->name,
                    'no_hp'          => $request->no_hp,
                    'alamat_lengkap' => $request->alamat_lengkap,
                    'kode_pos'       => $request->kode_pos,
                    'latitude'       => $request->latitude  ?: null,
                    'longitude'      => $request->longitude ?: null,
                    'alamat_utama'   => 1,
                ]);
            }
            // Untuk admin/penjual, tidak perlu membuat data alamat

            DB::commit();

            return redirect()->route('login')
                ->with('success', 'Registrasi berhasil! Silakan login.');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()
                ->withErrors(['error' => 'Registrasi gagal: ' . $e->getMessage()])
                ->withInput();
        }
    }

    /**
     * API endpoint untuk mendapatkan cities berdasarkan province (AJAX)
     */
    public function getCities(Request $request)
    {
        $cities = \Laravolt\Indonesia\Models\City::where('province_code', $request->province_code)
            ->orderBy('name')
            ->get();

        return response()->json($cities);
    }

    /**
     * API endpoint untuk mendapatkan districts berdasarkan city (AJAX)
     */
    public function getDistricts(Request $request)
    {
        $districts = \Laravolt\Indonesia\Models\District::where('city_code', $request->city_code)
            ->orderBy('name')
            ->get();

        return response()->json($districts);
    }

    /**
     * API endpoint untuk mendapatkan villages berdasarkan district (AJAX)
     */
    public function getVillages(Request $request)
    {
        $villages = \Laravolt\Indonesia\Models\Village::where('district_code', $request->district_code)
            ->orderBy('name')
            ->get();

        return response()->json($villages);
    }
}