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

class Admin_model extends CI_Model {
    
    public function __construct() {
       log_message('info', 'Admin Model Class Initialized');
    }
    
   public function validate_admin($username, $password) {
    log_message('info', 'Attempting to validate admin: ' . $username);
    
    $this->db->where('username', $username);
    $query = $this->db->get('admin_users');
    
    log_message('info', 'Query result count: ' . $query->num_rows());
    
    if ($query->num_rows() == 1) {
        $admin = $query->row();
        log_message('info', 'Found admin user: ' . $admin->username);
        log_message('info', 'Stored password hash: ' . $admin->password);
        
        // Verify password
        if (password_verify($password, $admin->password)) {
            log_message('info', 'Password verification successful');
            return $admin;
        } else {
            log_message('info', 'Password verification failed');
            
            // Fallback for plain text passwords (remove after migration)
            if ($admin->password === $password) {
                log_message('info', 'Plain text password match (legacy)');
                return $admin;
            }
        }
    }
    
    log_message('info', 'Admin validation failed');
    return false;
}
    public function update_password($admin_id, $new_password) {
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        $this->db->where('id', $admin_id);
        return $this->db->update('admin_users', array('password' => $hashed_password));
    }
    
    public function create_admin($username, $password, $email) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $data = array(
            'username' => $username,
            'password' => $hashed_password,
            'email' => $email,
            'created_at' => date('Y-m-d H:i:s')
        );
        return $this->db->insert('admin_users', $data);
    }
}
?>