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

/**
 * Super Admin Auth Controller
 */
class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('superadmin/Super_admin_model');
    }

    public function login() {
        // Redirect if already logged in
        if ($this->session->userdata('super_admin_logged_in') === TRUE) {
            redirect('superadmin/dashboard');
        }

        if ($this->input->method() == 'post') {
            $this->_handle_login();
        } else {
            $this->load->view('superadmin/auth/login');
        }
    }

    private function _handle_login() {
        $username = $this->input->post('username');
        $password = $this->input->post('password');

        $admin = $this->Super_admin_model->verify_login($username, $password);

        if ($admin) {
            $session_data = [
                'super_admin_id' => $admin->id,
                'super_admin_username' => $admin->username,
                'super_admin_email' => $admin->email,
                'super_admin_logged_in' => TRUE
            ];
            $this->session->set_userdata($session_data);

            // Log activity
            $this->Super_admin_model->log_activity('login', 'Super admin logged in');

            $this->session->set_flashdata('success', 'Welcome back, ' . $admin->username . '!');
            redirect('superadmin/dashboard');
        } else {
            $this->session->set_flashdata('error', 'Invalid username or password.');
            redirect('superadmin/auth/login');
        }
    }

    public function logout() {
        if ($this->session->userdata('super_admin_logged_in') === TRUE) {
            $this->Super_admin_model->log_activity('logout', 'Super admin logged out');
            
            // Only clear super admin session data, keep regular admin session
            $this->session->unset_userdata([
                'super_admin_id',
                'super_admin_username', 
                'super_admin_email',
                'super_admin_logged_in'
            ]);
        }
        redirect('superadmin/auth/login');
    }
}
