<?php

namespace App\Http\Controllers;

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

class OwnerRegistrationController extends Controller
{
    public function create()
    {
        return view('frontend.owner_register');
    }

    public function store(Request $request)
    {
        // 1. Siapkan Pesan Error Kustom (Bahasa Indonesia)
        $messages = [
            'name.required' => 'Nama lengkap wajib diisi.',
            'email.required' => 'Email wajib diisi.',
            'email.unique' => 'Email ini sudah terdaftar di sistem (sebagai Penyewa). Sesuai kebijakan pemisahan akun, harap gunakan alamat email yang BERBEDA untuk akun Mitra/Owner.',
            'phone.required' => 'Nomor WhatsApp wajib diisi.',
            'nik.required' => 'NIK wajib diisi.',
            'nik.size' => 'NIK harus tepat 16 digit angka.',
            'nik.unique' => 'NIK ini sudah terdaftar di sistem kami.',
            'ktp_image.required' => 'Foto KTP wajib diunggah.',
            'ktp_image.image' => 'File KTP harus berupa gambar.',
            'ktp_image.max' => 'Ukuran foto KTP maksimal 2MB.',
            'password.required' => 'Kata sandi wajib diisi.',
            'password.min' => 'Kata sandi minimal 8 karakter.',
            'password.confirmed' => 'Konfirmasi kata sandi tidak cocok.',
        ];

        // 2. Validasi Input (Sisipkan $messages di parameter kedua)
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
            'phone' => ['required', 'string', 'max:20'],
            'nik' => ['required', 'string', 'size:16', 'unique:users,nik'],
            'ktp_image' => ['required', 'image', 'mimes:jpg,jpeg,png', 'max:2048'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ], $messages);

        // 3. Upload File KTP
        $ktpPath = null;
        if ($request->hasFile('ktp_image')) {
            $ktpPath = $request->file('ktp_image')->store('ktp_verifications', 'public');
        }

        // 4. Buat User Baru
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'nik' => $request->nik,
            'ktp_image' => $ktpPath,
            'password' => Hash::make($request->password),
            'approval_status' => 'pending',
        ]);

        // 5. Berikan Role "Owner" (Pastikan "Owner" kapital sesuai database Anda)
        $user->assignRole('Owner');

        // 6. Redirect dengan popup sukses
        return redirect()->route('home')->with('success', 'Pendaftaran berhasil dikirim! Akun Anda sedang dalam tahap peninjauan. Kami akan menghubungi Anda melalui WhatsApp jika disetujui.');
    }
}
