<?php
class Auth extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('User_model');
    }

    public function login() {
        if ($_POST) {
            $email = $this->input->post('email');
            $password = $this->input->post('password');
            $user = $this->User_model->get_by_email($email);

            if ($user && password_verify($password, $user->password)) {
                if ($user->is_active == 0) {
                    $this->session->set_flashdata('error', 'Your account is inactive. Please contact admin.');
                    redirect('auth/login');
                }

                // Set session if active
                $this->session->set_userdata([
                    'user_id' => $user->id,
                    'role_id' => $user->role_id
                ]);
                redirect('dashboard');
            } else {
                $this->session->set_flashdata('error', 'Invalid credentials');
                redirect('auth/login');
            }
        }

        $this->load->view('auth/login');
    }

    public function register() {
        if ($_POST) {
            $data = [
                'name' => $this->input->post('name'),
                'email' => $this->input->post('email'),
                'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT),
                'role_id' => 2, // Default role for new users
                'is_active' => 0 // User starts inactive by default
            ];

            $this->User_model->insert($data);
            $this->session->set_flashdata('success', 'Registered successfully. Await admin activation.');
            redirect('auth/login');
        }

        $this->load->view('auth/register');
    }

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