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

class Login extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('user/User_model');
        $this->load->library('session');
        $this->load->helper(array('url','form','security'));
    }

    public function index() {
        if ($this->session->userdata('user_logged_in')) {
            redirect('user/dashboard');
        }

        $data = [];
        if ($this->session->flashdata('success')) {
            $data['success'] = $this->session->flashdata('success');
        }

        $this->load->view('user/login', $data);
    }

    public function process() {
        $email = $this->input->post('email', true);
        $password = $this->input->post('password', true);

        $user = $this->User_model->get_by_email($email);

        if ($user && password_verify($password, $user->password)) {
            // ✅ simpan juga id_kos ke session
            $this->session->set_userdata([
                'user_logged_in' => true,
                'user_id' => $user->id_penghuni,
                'user_name' => $user->nama_penghuni,
                'user_email' => $user->email,
                'id_kos' => $user->id_kos   // <── tambahkan ini
            ]);
            redirect('user/dashboard');
        } else {
            $data['error'] = 'Email atau password salah.';
            $this->load->view('user/login', $data);
        }
    }

    public function logout() {
        $this->session->sess_destroy();
        redirect('user/login');
    }
}
