<?php

namespace App\Http\Controllers;

use App\Models\Notification;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\Rules\Password as PasswordRule;

class RegisterController extends Controller
{
    public function show()
    {
        return view('auth.register');
    }

    public function store(Request $request)
    {
        // Build validation rules dynamically depending on schema
        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255'],
            'password' => ['required', 'confirmed', PasswordRule::min(8)],
        ];

        if (Schema::hasTable('users') && Schema::hasColumn('users', 'nik')) {
            $rules['nik'] = ['required', 'string', 'max:32', 'regex:/^[a-zA-Z0-9]+$/'];
        }
        if (Schema::hasTable('users') && Schema::hasColumn('users', 'username')) {
            $rules['username'] = ['nullable', 'string', 'max:255'];
        }
        if (Schema::hasTable('users') && Schema::hasColumn('users', 'skill')) {
            $rules['skill'] = ['required', 'string', 'in:mechanic,welder'];
        }
        $validated = $request->validate($rules);

        // Hapus akun lama yang belum verified (email_verified_at = null) dengan credential yang sama
        User::where('email_verified_at', null)
            ->where(function ($q) use ($validated) {
                $q->where('email', $validated['email']);
                
                if (Schema::hasColumn('users', 'nik') && isset($validated['nik'])) {
                    $q->orWhere('nik', $validated['nik']);
                }
                
                if (Schema::hasColumn('users', 'username') && isset($validated['username']) && $validated['username']) {
                    $q->orWhere('username', $validated['username']);
                }
            })
            ->delete();

        // Check apakah email/nik/username sudah ada dan VERIFIED
        if (User::where('email', $validated['email'])->where('email_verified_at', '!=', null)->exists()) {
            return back()->withErrors(['email' => 'Email sudah terdaftar dan terverifikasi.'])->withInput();
        }

        if (Schema::hasColumn('users', 'nik') && isset($validated['nik'])) {
            if (User::where('nik', $validated['nik'])->where('email_verified_at', '!=', null)->exists()) {
                return back()->withErrors(['nik' => 'NIK sudah terdaftar.'])->withInput();
            }
        }

        if (Schema::hasColumn('users', 'username') && isset($validated['username']) && $validated['username']) {
            if (User::where('username', $validated['username'])->where('email_verified_at', '!=', null)->exists()) {
                return back()->withErrors(['username' => 'Username sudah terdaftar.'])->withInput();
            }
        }

        // Generate kode OTP 6 digit
        $otp = random_int(100000, 999999);

        $attrs = [
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => $validated['password'], // auto hashed via cast in User model
            'role' => 'pegawai',
            'email_verification_code' => $otp,
        ];

        if (Schema::hasColumn('users', 'nik')) {
            $attrs['nik'] = $validated['nik'];
        }
        if (Schema::hasColumn('users', 'is_approved')) {
            $attrs['is_approved'] = false;
        }
        if (Schema::hasTable('users') && Schema::hasColumn('users', 'username')) {
            $attrs['username'] = $validated['username'] ?? null;
        }

        if (Schema::hasColumn('users', 'skill')) {
            $attrs['skill'] = $validated['skill'];
        }

        $user = User::create($attrs);

        // Kirim email OTP ke user dari email institusi
        try {
            \Mail::mailer('smtp')->to($user->email)
                ->send((new \App\Mail\EmailVerificationCode($otp))
                ->from('e31221353@student.polije.ac.id', 'Absensi PT. Triatra'));
        } catch (\Exception $e) {
            \Log::error('Gagal mengirim email verifikasi: ' . $e->getMessage());
        }

        if (Schema::hasTable('notifications')) {
            $adminRecipients = User::query()
                ->whereIn('role', ['admin', 'atasan'])
                ->get(['id', 'name']);

            foreach ($adminRecipients as $admin) {
                Notification::create([
                    'user_id' => $admin->id,
                    'title' => 'Pengguna baru menunggu persetujuan',
                    'message' => 'Akun ' . $user->name . ' membutuhkan persetujuan sebelum dapat login.',
                    'type' => 'user_approval',
                    'is_read' => false,
                ]);
            }
        }

        // Redirect ke halaman verifikasi OTP, bawa email sebagai parameter
        return redirect()->route('verification.form', ['email' => $user->email]);
    }
}
