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

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        
        // Load library yang diperlukan
        $this->load->library('session');
        $this->load->library('form_validation');
        
        // Load model
        $this->load->model('User_model');
    }

    public function index() {
        // Cek jika sudah login
        if($this->session->userdata('logged_in')) {
            redirect('dashboard');
        }
        $this->load->view('auth/login');
    }

    public function login() {
        // Set rules validasi
        $this->form_validation->set_rules('username', 'Username', 'required|trim');
        $this->form_validation->set_rules('password', 'Password', 'required|trim');

        if($this->form_validation->run() == FALSE) {
            // Jika validasi gagal, tampilkan form login lagi
            $this->load->view('auth/login');
        } else {
            $username = $this->input->post('username', TRUE);
            $password = $this->input->post('password', TRUE);

            $user = $this->User_model->check_login($username, $password);

            if($user) {
                // Set session data - PENTING: role harus di-set!
                $session_data = array(
                    'user_id' => $user->id,
                    'username' => $user->username,
                    'nama' => $user->nama_lengkap,
                    'role' => $user->role, // admin atau warga
                    'logged_in' => TRUE
                );
                
                $this->session->set_userdata($session_data);
                
                // Log aktivitas
                $this->User_model->log_activity($user->id, 'login', 'User login ke sistem');
                
                // Set flashdata success
                $this->session->set_flashdata('success', 'Selamat datang, ' . $user->nama_lengkap . '!');
                
                redirect('dashboard');
            } else {
                // Login gagal
                $this->session->set_flashdata('error', 'Username atau Password salah!');
                redirect('auth');
            }
        }
    }

public function logout() {
    $user_id = $this->session->userdata('user_id');
    
    // Cek user masih ada di database sebelum log
    if($user_id) {
        $cek = $this->db->get_where('users', ['id' => $user_id])->row();
        if($cek) {
            $this->User_model->log_activity(
                $user_id, 
                'logout', 
                'User logout dari sistem'
            );
        }
    }
    
    // Hapus semua session
    $this->session->sess_destroy();
    $this->session->set_flashdata('success', 'Anda berhasil logout!');
    redirect('auth');
}

    public function register() {
        // Jika sistem membolehkan register sendiri
        // Jika tidak, comment method ini
        
        if($this->input->post()) {
            $this->form_validation->set_rules('username', 'Username', 'required|trim|is_unique[users.username]');
            $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
            $this->form_validation->set_rules('password_confirm', 'Konfirmasi Password', 'required|matches[password]');
            $this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required|trim');
            
            if($this->form_validation->run()) {
                $data = array(
                    'username' => $this->input->post('username'),
                    'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT),
                    'nama_lengkap' => $this->input->post('nama_lengkap'),
                    'role' => 'warga', // Default role warga untuk registrasi
                    // 'created_at' => date('Y-m-d H:i:s')
                    'updated_at' => app_now()
                );
                
                if($this->User_model->insert($data)) {
                    $this->session->set_flashdata('success', 'Registrasi berhasil! Silakan login.');
                    redirect('auth');
                } else {
                    $this->session->set_flashdata('error', 'Gagal melakukan registrasi!');
                }
            }
        }
        
        $data['title'] = 'Register';
        $this->load->view('auth/register', $data);
    }

    public function forgot_password() {
        // Implementasi lupa password
        // Bisa kirim email atau reset manual oleh admin
        
        $data['title'] = 'Lupa Password';
        $this->load->view('auth/forgot_password', $data);
    }
}