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

class Admin_model extends CI_Model {
    
    public function __construct() {
        parent::__construct();
    }
    
    // Login verification
    public function check_login($username, $password) {
        $this->db->where('username', $username);
        $this->db->where('is_active', 1);
        $query = $this->db->get('tbl_admin');
        
        if ($query->num_rows() == 1) {
            $admin = $query->row();
            if (password_verify($password, $admin->password)) {
                // Update last login
                $this->db->where('id', $admin->id);
                $this->db->update('tbl_admin', array('last_login' => date('Y-m-d H:i:s')));
                
                return $admin;
            }
        }
        return false;
    }
    
    // Get all admins
    public function get_all_admins() {
        return $this->db->get('tbl_admin')->result();
    }
    
    // Get admin by ID
    public function get_admin_by_id($id) {
        $this->db->where('id', $id);
        return $this->db->get('tbl_admin')->row();
    }
    
    // Add new admin
    public function add_admin($data) {
        // Hash password
        if (isset($data['password'])) {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        return $this->db->insert('tbl_admin', $data);
    }
    
    // Update admin
    public function update_admin($id, $data) {
        // Hash password if provided
        if (isset($data['password']) && !empty($data['password'])) {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        } else {
            unset($data['password']);
        }
        
        $this->db->where('id', $id);
        return $this->db->update('tbl_admin', $data);
    }
    
    // Delete admin
    public function delete_admin($id) {
        $this->db->where('id', $id);
        return $this->db->delete('tbl_admin');
    }
    
    // Check if username exists
    public function username_exists($username, $id = null) {
        $this->db->where('username', $username);
        if ($id) {
            $this->db->where('id !=', $id);
        }
        return $this->db->get('tbl_admin')->num_rows() > 0;
    }
}