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

/**
 * Super Admin Model
 */
class Super_admin_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    public function verify_login($username, $password) {
        $admin = $this->db->where('username', $username)
                          ->where('status', 'active')
                          ->get('super_admins')
                          ->row();

        if ($admin && password_verify($password, $admin->password)) {
            $this->db->where('id', $admin->id);
            $this->db->update('super_admins', ['last_login' => date('Y-m-d H:i:s')]);
            return $admin;
        }

        return false;
    }

    public function get($id) {
        return $this->db->where('id', $id)->get('super_admins')->row();
    }
    
    public function get_by_id($id) {
        return $this->get($id);
    }

    public function update_password($id, $new_password) {
        $this->db->where('id', $id);
        return $this->db->update('super_admins', [
            'password' => password_hash($new_password, PASSWORD_DEFAULT)
        ]);
    }

    public function log_activity($action_type, $description = null, $portal_code = null) {
        return $this->db->insert('portal_activity_logs', [
            'portal_code' => $portal_code,
            'super_admin_id' => $this->session->userdata('super_admin_id'),
            'action_type' => $action_type,
            'description' => $description,
            'ip_address' => $this->input->ip_address()
        ]);
    }

    public function get_activity_logs($portal_code = null, $limit = 50, $offset = 0) {
        $this->db->select('pal.*, p.portal_name, sa.username as admin_name');
        $this->db->from('portal_activity_logs pal');
        $this->db->join('portals p', 'p.portal_code = pal.portal_code', 'left');
        $this->db->join('super_admins sa', 'sa.id = pal.super_admin_id', 'left');
        
        if ($portal_code) {
            $this->db->where('pal.portal_code', $portal_code);
        }
        
        $this->db->order_by('pal.created_at', 'DESC');
        $this->db->limit($limit, $offset);
        
        return $this->db->get()->result();
    }
}
