<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Register extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('admin/Admin_model');
        $this->load->library(['session', 'form_validation']);
        $this->load->helper(array('url', 'form', 'security'));
    }

    /**
     * Tampilkan halaman register
     */
    public function index()
    {
        if ($this->session->userdata('admin_logged_in')) {
            redirect('admin/dashboard');
        }

        $this->load->view('admin/register'); // Buat view register sendiri nanti
    }

    /**
     * Proses registrasi admin baru
     */
    public function process()
    {
        // Validasi form
        $this->form_validation->set_rules('nama', 'Nama', 'required|trim');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[admin.email]');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
        $this->form_validation->set_rules('confirm_password', 'Konfirmasi Password', 'required|matches[password]');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('admin/register');
            return;
        }

        // Ambil data input
        $nama     = $this->input->post('nama', true);
        $email    = $this->input->post('email', true);
        $password = password_hash($this->input->post('password', true), PASSWORD_BCRYPT);

        // Simpan ke database
        $data = [
            'nama' => $nama,
            'email' => $email,
            'password' => $password,
            'created_at' => date('Y-m-d H:i:s')
        ];

        $insert_id = $this->Admin_model->insert($data);

        if ($insert_id) {
            // Buat session login langsung setelah register
            $this->session->set_userdata([
                'admin_logged_in' => true,
                'admin_id' => $insert_id,
                'admin_name' => $nama,
                'id_kos' => null // belum punya kos
            ]);

            // Arahkan ke halaman tambah kos
            $this->session->set_flashdata('success', 'Registrasi berhasil! Silakan buat kos pertama Anda.');
            redirect('admin/kos/tambah');
        } else {
            $this->session->set_flashdata('error', 'Terjadi kesalahan saat menyimpan data.');
            redirect('admin/register');
        }
    }
}
