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

class Kos extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('admin/Kos_model'); // ✅ sesuai folder
        $this->load->library('session');
        if (!$this->session->userdata('admin_id')) {
            redirect('user/login');
        }
    }

    public function index()
    {
        $id_admin = $this->session->userdata('admin_id');
        $data['kos_list'] = $this->Kos_model->get_by_admin($id_admin);
        $this->load->view('admin/kos/index', $data);
    }

    public function tambah()
    {
        if ($this->input->post()) {
            $data = [
                'id_admin' => $this->session->userdata('admin_id'),
                'nama_kos' => $this->input->post('nama_kos'),
                'alamat' => $this->input->post('alamat'),
                'jumlah_kamar' => $this->input->post('jumlah_kamar'),
                'deskripsi' => $this->input->post('deskripsi'),
                'status' => $this->input->post('status'),
            ];

            $this->Kos_model->insert($data);
            $this->session->set_flashdata('success', 'Kos berhasil ditambahkan.');
            redirect('admin/dashboard');
        } else {
            $this->load->view('admin/kos/tambah');
        }
    }

    public function edit($id)
    {
        $data['kos'] = $this->Kos_model->get_by_id($id);

        if (!$data['kos']) {
            show_404();
        }

        if ($this->input->post()) {
            $update = [
                'nama_kos' => $this->input->post('nama_kos'),
                'alamat' => $this->input->post('alamat'),
                'jumlah_kamar' => $this->input->post('jumlah_kamar'),
                'deskripsi' => $this->input->post('deskripsi'),
                'status' => $this->input->post('status'),
            ];

            $this->Kos_model->update($id, $update);
            $this->session->set_flashdata('success', 'Data kos berhasil diperbarui.');
            redirect('admin/kos');
        } else {
            $this->load->view('admin/kos/edit', $data);
        }
    }

    public function hapus($id)
    {
        $this->Kos_model->delete($id);
        $this->session->set_flashdata('success', 'Kos berhasil dihapus.');
        redirect('admin/kos');
    }
}
