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

class User_model extends CI_Model {

    private $table = 'kns1_users';

    public function validate_credentials($where)
    {
        $query = $this->db->get_where($this->table, $where);
        return $query->row() ?: false;
    }

    /**
     * Look up a single user by email OR username (for login verification).
     */
    public function find_by_email_or_username($login)
    {
        $this->db->group_start()
                 ->where('email', $login)
                 ->or_where('username', $login)
                 ->group_end();
        return $this->db->get($this->table)->row();
    }

    /**
     * Standard password hashing for new/updated passwords (bcrypt).
     */
    public static function hash_password($plain)
    {
        return password_hash($plain, PASSWORD_BCRYPT);
    }

    /**
     * Verify a password against a stored hash.
     * Supports current bcrypt hashes and legacy md5('kns1'.pw.'qurbani') hashes.
     */
    public static function verify_password($plain, $stored)
    {
        if (is_string($stored) && strlen($stored) === 60 && strpos($stored, '$2') === 0) {
            return password_verify($plain, $stored);
        }
        return hash_equals((string)$stored, md5('kns1' . $plain . 'qurbani'));
    }

    public function create($data)
    {
        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }

    public function update($id, $data)
    {
        $this->db->where('id', $id)->update($this->table, $data);
        return $this->db->affected_rows();
    }

    public function destroy($id)
    {
        $this->db->where('id', $id)->delete($this->table);
        return $this->db->affected_rows();
    }

    public function get_by($id)
    {
        return $this->db->get_where($this->table, ['id' => $id])->row();
    }

    public function get_all($limit = null, $offset = null)
    {
        $this->db->order_by('id', 'DESC');
        return $this->db->get($this->table, $limit, $offset)->result();
    }

    public function checkEmail($email, $exclude_id = null)
    {
        $this->db->where('email', $email);
        if ($exclude_id) {
            $this->db->where('id !=', $exclude_id);
        }
        return $this->db->get($this->table)->num_rows() > 0;
    }

    public function checkUsername($username, $exclude_id = null)
    {
        $this->db->where('username', $username);
        if ($exclude_id) {
            $this->db->where('id !=', $exclude_id);
        }
        return $this->db->get($this->table)->num_rows() > 0;
    }

    public function getNameBy($id)
    {
        $this->db->select('name')->where('id', $id);
        $row = $this->db->get($this->table)->row();
        return $row ? $row->name : null;
    }

    public function has_permission($controller, $method)
{
    $role = $_SESSION['qurbani_role'] ?? null;
    if (!$role) return false;

    $this->db->select('rp.id');
    $this->db->from('kns1_roles r');
    $this->db->join('kns1_role_permissions rp', 'rp.role_id = r.id');
    $this->db->join('kns1_permissions p', 'p.id = rp.permission_id');
    $this->db->where('r.name', $role);
    $this->db->where('p.controller', $controller);
    $this->db->where('p.method', $method);

    return $this->db->get()->num_rows() > 0;
}



public function get_logged_in_users_count()
{
    $this->db->where('is_logged_in', 1);
    return $this->db->count_all_results('kns1_users');
}

public function get_last_month_login_count()
{
    $lastMonth = date('Y-m-01 00:00:00', strtotime('first day of last month'));
    $thisMonth = date('Y-m-01 00:00:00');

    $this->db->where('updated_at >=', $lastMonth);
    $this->db->where('updated_at <', $thisMonth);
    return $this->db->count_all_results('kns1_users');
}

public function get_total_users_count()
{
    return $this->db->count_all('kns1_users');
}



    public function get_all_logs()
    {
        $this->db->select('l.*, u.name, u.email');
        $this->db->from('kns1_login_logs l');
        $this->db->join('kns1_users u', 'u.id = l.user_id', 'left');
        $this->db->order_by('l.login_time', 'DESC');
        return $this->db->get()->result();
    }

public function get_daily_stats($days = 7)
{
    $from = date('Y-m-d 00:00:00', strtotime("-$days days"));
    $to = date('Y-m-d 23:59:59');

    $this->db->select("DATE(login_time) as date,
        SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_count,
        SUM(CASE WHEN status = 'failure' THEN 1 ELSE 0 END) as failure_count");
    $this->db->where('login_time >=', $from);
    $this->db->where('login_time <=', $to);
    $this->db->group_by('DATE(login_time)');
    $this->db->order_by('DATE(login_time)', 'ASC');
    return $this->db->get('kns1_login_logs')->result();
}

// Total logins for each user
public function get_user_login_count($user_id)
{
    $this->db->where('user_id', $user_id);
    $this->db->where('status', 'success');
    return $this->db->count_all_results('kns1_login_logs');
}

// Last login datetime
public function get_user_last_login($user_id)
{
    $this->db->where('user_id', $user_id);
    $this->db->where('status', 'success');
    $this->db->order_by('login_time', 'DESC');
    $this->db->limit(1);
    $query = $this->db->get('kns1_login_logs');
    return $query->row();
}

// Was user active in last 30 days?
public function is_user_active_last_30_days($user_id)
{
    $last30 = date('Y-m-d H:i:s', strtotime('-30 days'));
    $this->db->where('user_id', $user_id);
    $this->db->where('status', 'success');
    $this->db->where('login_time >=', $last30);
    return $this->db->count_all_results('kns1_login_logs') > 0;
}

// In User_model.php
public function get_most_active_user() {
    $this->db->select('kns1_users.*, COUNT(kns1_login_logs.id) as login_count');
    $this->db->join('kns1_login_logs', 'kns1_login_logs.user_id = kns1_users.id');
    $this->db->where('kns1_login_logs.status', 'success');
    $this->db->group_by('kns1_users.id');
    $this->db->order_by('login_count', 'DESC');
    $this->db->limit(1);
    return $this->db->get('kns1_users')->row();
}



public function get_failed_logins_today() {
    $today = date('Y-m-d');
    $this->db->where('status', 'failure');
    $this->db->where('DATE(login_time)', $today);
    return $this->db->count_all_results('kns1_login_logs');
}



public function get_last_logout_time() {
    $this->db->select_max('logout_time');
    $this->db->where('logout_time IS NOT NULL', null, false);
    $result = $this->db->get('kns1_login_logs')->row();
    return $result->logout_time ?? null;
}


public function get_avg_session_duration() {
    $this->db->select('AVG(TIMESTAMPDIFF(SECOND, login_time, logout_time)) as avg_seconds');
    $this->db->where("logout_time IS NOT NULL", null, false);
    $result = $this->db->get('kns1_login_logs')->row();
    if ($result && $result->avg_seconds) {
        $minutes = floor($result->avg_seconds / 60);
        $seconds = $result->avg_seconds % 60;
        return $minutes . ' mins ' . $seconds . ' secs';
    }
    return "0 mins";
}



public function get_daily_login_counts($days = 30)
{
    $this->db->select("DATE(login_time) as date, COUNT(*) as total")
             ->from('kns1_login_logs')
             ->where("status", "success")
             ->where("login_time >=", date('Y-m-d', strtotime("-{$days} days")))
             ->group_by("DATE(login_time)")
             ->order_by("DATE(login_time)", "ASC");

    $result = $this->db->get()->result();

    $data = [];
    foreach ($result as $row) {
        $data[date('d M', strtotime($row->date))] = (int)$row->total;
    }

    // Fill missing days with 0
    $filled = [];
    for ($i = $days - 1; $i >= 0; $i--) {
        $day = date('d M', strtotime("-$i days"));
        $filled[] = [
            'date' => $day,
            'count' => isset($data[$day]) ? $data[$day] : 0
        ];
    }

    return $filled;
}




}
