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

class Register extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        // 🔥 Load model dan helper/library yang dibutuhkan
        $this->load->model('user/Penghuni_model');
        $this->load->model('user/User_model');
        $this->load->helper(['url', 'form']);
        $this->load->library(['session', 'form_validation']);
    }

    /**
     * 🔹 Tampilkan halaman registrasi
     */
    public function index()
    {
        $data['error'] = $this->session->flashdata('error');
        $data['success'] = $this->session->flashdata('success');
        $data['list_kos'] = $this->User_model->get_all_kos(); // 🔥 Ambil data kos
        $this->load->view('user/register', $data);
    }

    /**
     * 🔹 Cek ketersediaan kamar via AJAX
     */
    public function check_kamar()
    {
        header('Content-Type: application/json');
        $kamar = $this->input->post('kamar', true);

        if (empty($kamar)) {
            echo json_encode([
                'available' => false,
                'message' => 'Nomor kamar tidak boleh kosong'
            ]);
            return;
        }

        $exists = $this->Penghuni_model->kamar_exists($kamar);

        echo json_encode([
            'available' => !$exists,
            'kamar' => $kamar,
            'message' => $exists ? 'Kamar sudah terisi' : 'Kamar tersedia'
        ]);
    }

    /**
     * 🔹 Ambil daftar kamar yang masih kosong (AJAX)
     */
    public function get_available_kamar()
    {
        header('Content-Type: application/json');

        // Ambil semua kamar yang sudah terisi
        $occupied_kamar = $this->Penghuni_model->get_occupied_kamar();

        // Generate semua kamar yang tersedia
        $all_kamar = $this->generate_all_kamar();

        // Filter hanya yang belum terisi
        $available_kamar = array_diff($all_kamar, $occupied_kamar);
        sort($available_kamar);

        echo json_encode([
            'success' => true,
            'kamar' => array_values($available_kamar)
        ]);
    }

    /**
     * 🔹 Generate daftar kamar (misalnya A-01 sampai C-10)
     */
    private function generate_all_kamar()
    {
        $kamar_list = [];
        $lantai = ['A', 'B', 'C'];
        $jumlah_per_lantai = 10;

        foreach ($lantai as $floor) {
            for ($i = 1; $i <= $jumlah_per_lantai; $i++) {
                $kamar_list[] = $floor . '-' . str_pad($i, 2, '0', STR_PAD_LEFT);
            }
        }
        return $kamar_list;
    }

    /**
     * 🔹 Proses registrasi penghuni baru
     */
    public function process()
    {
        $nama_penghuni = trim($this->input->post('nama_penghuni', true));
        $email = trim($this->input->post('email', true));
        $password = trim($this->input->post('password', true));
        $no_hp = trim($this->input->post('no_hp', true));
        $kamar = trim($this->input->post('kamar', true));
        $alamat = trim($this->input->post('alamat', true));
        $id_kos = trim($this->input->post('id_kos', true));

        // Validasi dasar
        if (empty($nama_penghuni) || empty($email) || empty($password) || empty($kamar) || empty($id_kos)) {
            $this->session->set_flashdata('error', 'Nama, Email, Password, Kos, dan Kamar harus diisi!');
            redirect(site_url('user/register'));
            return;
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->session->set_flashdata('error', 'Format email tidak valid!');
            redirect(site_url('user/register'));
            return;
        }

        if ($this->Penghuni_model->email_exists($email)) {
            $this->session->set_flashdata('error', 'Email sudah terdaftar!');
            redirect(site_url('user/register'));
            return;
        }

        // Cek ketersediaan kamar di kos yang dipilih
        if ($this->Penghuni_model->kamar_exists_in_kos($kamar, $id_kos)) {
            $this->session->set_flashdata('error', 'Kamar ' . $kamar . ' sudah terisi di kos ini!');
            redirect(site_url('user/register'));
            return;
        }

        // 🔥 Ambil id_admin dari tabel kos berdasarkan id_kos yang dipilih
        $this->load->database();
        $kos_data = $this->db->get_where('kos', ['id_kos' => $id_kos])->row();

        if (!$kos_data) {
            $this->session->set_flashdata('error', 'Kos tidak ditemukan!');
            redirect(site_url('user/register'));
            return;
        }

        $id_admin = $kos_data->id_admin;

        $hashed_password = password_hash($password, PASSWORD_BCRYPT);

        $data = [
            'nama_penghuni' => $nama_penghuni,
            'email' => $email,
            'password' => $hashed_password,
            'no_hp' => $no_hp,
            'kamar' => $kamar,
            'alamat' => $alamat,
            'id_kos' => $id_kos,
            'id_admin' => $id_admin, // 🔥 Simpan id_admin yang sesuai
            'created_at' => date('Y-m-d H:i:s')
        ];

        $insert_id = $this->Penghuni_model->insert_penghuni($data);

        if ($insert_id) {
            $this->session->set_flashdata('success', 'Registrasi berhasil! Silakan login.');
            redirect(site_url('user/login'));
        } else {
            $this->session->set_flashdata('error', 'Registrasi gagal! Silakan coba lagi.');
            redirect(site_url('user/register'));
        }
    }

    /**
     * 🔹 Cek ketersediaan kamar per kos (AJAX)
     */
    public function check_kamar_per_kos()
    {
        header('Content-Type: application/json');
        $id_kos = $this->input->post('id_kos', true);
        $kamar = $this->input->post('kamar', true);

        if (empty($id_kos) || empty($kamar)) {
            echo json_encode(['available' => false, 'message' => 'Kos dan kamar harus dipilih']);
            return;
        }

        $this->load->database();
        $kos = $this->db->get_where('kos', ['id_kos' => $id_kos])->row();
        if (!$kos) {
            echo json_encode(['available' => false, 'message' => 'Kos tidak ditemukan']);
            return;
        }

        $jumlah_kamar = (int)$kos->jumlah_kamar;
        $nomor_kamar = (int)filter_var($kamar, FILTER_SANITIZE_NUMBER_INT);

        if ($nomor_kamar < 1 || $nomor_kamar > $jumlah_kamar) {
            echo json_encode(['available' => false, 'message' => 'Nomor kamar tidak tersedia di kos ini']);
            return;
        }

        $exists = $this->db->get_where('penghuni', [
            'id_kos' => $id_kos,
            'kamar' => $kamar
        ])->num_rows() > 0;

        echo json_encode([
            'available' => !$exists,
            'message' => $exists ? 'Kamar sudah terisi' : 'Kamar tersedia'
        ]);
    }
}
