<?php
// app/Controllers/Frontend/RegistrationController.php

namespace App\Controllers\Frontend;

use App\Controllers\BaseController;
use App\Models\UserModel; // Pastikan UserModel di-import

class RegistrationController extends BaseController
{
    /**
     * Menampilkan halaman formulir registrasi.
     */
    public function showRegistrationForm()
    {
        return view('frontend/registration/new');
    }

    /**
     * Memproses data yang dikirim dari formulir registrasi.
     * ALUR BARU: Setelah sukses, langsung arahkan ke halaman verifikasi.
     */
    public function processRegistration()
    {
        // 1. Definisikan Aturan Validasi (tidak ada perubahan)
        $rules = [
            'name' => [
                'label' => 'Full Name',
                'rules' => 'required|alpha_space|min_length[3]|max_length[255]',
                'errors' => ['alpha_space' => 'The {field} field can only contain alphabetical characters and spaces.']
            ],
            'phone_number' => [
                'label' => 'WhatsApp Number',
                'rules' => 'required|regex_match[/^\+[1-9]\d{1,14}$/]|is_unique[users.phone_number]',
                'errors' => [
                    'regex_match' => 'The {field} must be in international format (e.g., +62812...).',
                    'is_unique'   => 'This {field} is already registered.'
                ]
            ],
            'email' => [
                'label' => 'Email',
                'rules' => 'required|valid_email|is_unique[users.email]',
                'errors' => ['is_unique' => 'This {field} is already registered.']
            ],
            'password' => [
                'label' => 'Password',
                'rules' => 'required|min_length[8]'
            ],
            'password_confirm' => [
                'label' => 'Password Confirmation',
                'rules' => 'required|matches[password]'
            ],
            'kta_number' => [
                'label' => 'KTA',
                'rules' => 'permit_empty|validate_kta_and_birthdate[birth_date]'
            ],
            'birth_date' => [
                'label' => 'Date of Birth',
                'rules' => 'permit_empty|valid_date'
            ],
        ];

        // 2. Jalankan Validasi (tidak ada perubahan)
        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        // 3. Jika Validasi Sukses, Simpan Data (status dihilangkan)
        $userModel = new UserModel();
        $data = [
            'name'           => $this->request->getPost('name'),
            'email'          => $this->request->getPost('email'),
            'phone_number'   => $this->request->getPost('phone_number'),
            'password'       => $this->request->getPost('password'),
            'kta_number'     => $this->request->getPost('kta_number'),
            'birth_date'     => $this->request->getPost('birth_date'),
        ];

        try {
            $userId = $userModel->insert($data, true); 

            // --- PERUBAHAN UTAMA DI SINI ---
            if ($userId) {
                // Jika user berhasil dibuat:
                // 1. Simpan ID user ke dalam sesi sementara untuk alur verifikasi.
                session()->setTempdata('verifying_user_id', $userId, 300); // Sesi berlaku 5 menit

                // 2. Langsung arahkan ke halaman pilihan verifikasi.
                return redirect()->to(route_to('verify.choice'));

            } else {
                // Jika insert gagal karena alasan lain (misal: error model)
                return redirect()->back()->withInput()->with('errors', $userModel->errors());
            }
        } catch (\Exception $e) {
            // Tangani error database atau lainnya
            log_message('error', 'User registration failed: ' . $e->getMessage());
            return redirect()->back()->withInput()->with('error', lang('Registration.registrationFailed'));
        }
    }

    // Metode logUserIn() tidak lagi diperlukan di controller ini dan bisa dihapus.
}