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

class User_model extends CI_Model {

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

    // ═══════════════════════════════════════
    // GET DATA
    // ═══════════════════════════════════════

    public function get_all() {
        $this->db->order_by('nama_lengkap', 'ASC');
        return $this->db->get('users')->result();
    }

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

    public function get_by_username($username) {
        return $this->db->get_where('users', ['username' => $username])->row();
    }

    public function get_by_role($role) {
        return $this->db->get_where('users', ['role' => $role])->result();
    }

    public function get_warga_users() {
        $this->db->select('u.*, w.nik, w.no_kk, w.tempat_lahir, w.tanggal_lahir,
                           w.jenis_kelamin, w.status_perkawinan, w.pekerjaan,
                           w.agama, w.status_domisili, w.status_hubungan');
        $this->db->from('users u');
        $this->db->join('warga w', 'w.user_id = u.id', 'left');
        $this->db->where('u.role', 'warga');
        $this->db->order_by('u.nama_lengkap', 'ASC');
        return $this->db->get()->result();
    }

    // ═══════════════════════════════════════
    // AUTH
    // ═══════════════════════════════════════

    public function check_login($username, $password) {
        $user = $this->db->get_where('users', [
            'username' => $username,
            'status'   => 'aktif'
        ])->row();

        if($user && password_verify($password, $user->password)) {
            return $user;
        }
        return false;
    }

    public function is_username_exists($username, $exclude_id = null) {
        $this->db->where('username', $username);
        if($exclude_id) {
            $this->db->where('id !=', $exclude_id);
        }
        return $this->db->count_all_results('users') > 0;
    }

    public function is_email_exists($email, $exclude_id = null) {
        $this->db->where('email', $email);
        if($exclude_id) {
            $this->db->where('id !=', $exclude_id);
        }
        return $this->db->count_all_results('users') > 0;
    }

    // ═══════════════════════════════════════
    // CRUD
    // ═══════════════════════════════════════

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

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

    public function delete($id) {
        // Lepas relasi warga sebelum hapus user
        $this->db->where('user_id', $id);
        $this->db->update('warga', ['user_id' => null]);

        $this->db->where('id', $id);
        return $this->db->delete('users');
    }

    public function update_password($id, $password) {
        $this->db->where('id', $id);
        return $this->db->update('users', [
            'password'   => password_hash($password, PASSWORD_DEFAULT),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    public function update_foto($id, $foto) {
        $this->db->where('id', $id);
        return $this->db->update('users', [
            'foto'       => $foto,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    public function update_status($id, $status) {
        $this->db->where('id', $id);
        return $this->db->update('users', [
            'status'     => $status,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    // ═══════════════════════════════════════
    // LOG AKTIVITAS
    // ═══════════════════════════════════════

    public function log_activity($user_id, $tipe, $aktivitas) {
        // Cek user masih ada sebelum insert log
        $cek = $this->db->get_where('users', ['id' => $user_id])->row();
        if(!$cek) return false;

        // Cek tabel log_aktivitas ada
        if(!$this->db->table_exists('log_aktivitas')) return false;

        return $this->db->insert('log_aktivitas', [
            'user_id'    => $user_id,
            'tipe'       => $tipe,
            'aktivitas'  => $aktivitas,
            'ip_address' => $this->input->ip_address(),
            'user_agent' => $this->input->user_agent(),
            'created_at' => date('Y-m-d H:i:s'),
        ]);
    }

    public function get_log_aktivitas($user_id = null, $limit = 20) {
        $this->db->select('l.*, u.nama_lengkap, u.role');
        $this->db->from('log_aktivitas l');
        $this->db->join('users u', 'u.id = l.user_id', 'left');
        if($user_id) {
            $this->db->where('l.user_id', $user_id);
        }
        $this->db->order_by('l.created_at', 'DESC');
        $this->db->limit($limit);
        return $this->db->get()->result();
    }

    public function count_all_logs() {
        return $this->db->count_all('log_aktivitas');
    }

    public function count_filtered_logs($search = '') {
        $this->db->from('log_aktivitas l');
        $this->db->join('users u', 'u.id = l.user_id', 'left');
        if($search) {
            $this->db->group_start();
            $this->db->like('u.nama_lengkap', $search);
            $this->db->or_like('l.tipe', $search);
            $this->db->or_like('l.aktivitas', $search);
            $this->db->or_like('l.ip_address', $search);
            $this->db->group_end();
        }
        return $this->db->count_all_results();
    }

    public function get_datatables_logs($start, $length, $search = '', $order_col = 0, $order_dir = 'desc') {
        $columns = [
            0 => 'l.created_at',
            1 => 'u.nama_lengkap',
            2 => 'l.tipe',
            3 => 'l.aktivitas',
            4 => 'l.ip_address'
        ];

        $this->db->select('l.*, u.nama_lengkap, u.role');
        $this->db->from('log_aktivitas l');
        $this->db->join('users u', 'u.id = l.user_id', 'left');

        if($search) {
            $this->db->group_start();
            $this->db->like('u.nama_lengkap', $search);
            $this->db->or_like('l.tipe', $search);
            $this->db->or_like('l.aktivitas', $search);
            $this->db->or_like('l.ip_address', $search);
            $this->db->group_end();
        }

        $sort_col = isset($columns[$order_col]) ? $columns[$order_col] : 'l.created_at';
        $this->db->order_by($sort_col, $order_dir);
        $this->db->limit($length, $start);
        
        return $this->db->get()->result();
    }

    public function cleanup_logs($days = 90) {
        $date = date('Y-m-d H:i:s', strtotime('-' . $days . ' days'));
        $this->db->where('created_at <', $date);
        return $this->db->delete('log_aktivitas');
    }

    public function clear_all_logs() {
        return $this->db->empty_table('log_aktivitas');
    }

    // ═══════════════════════════════════════
    // STATISTIK
    // ═══════════════════════════════════════

    public function count_by_role($role) {
        return $this->db->where('role', $role)
                        ->where('status', 'aktif')
                        ->count_all_results('users');
    }

    public function count_aktif() {
        return $this->db->where('status', 'aktif')
                        ->count_all_results('users');
    }

    public function count_nonaktif() {
        return $this->db->where('status', 'nonaktif')
                        ->count_all_results('users');
    }

    // ═══════════════════════════════════════
    // SEARCH
    // ═══════════════════════════════════════

    public function search($keyword) {
        $this->db->group_start();
            $this->db->like('nama_lengkap', $keyword);
            $this->db->or_like('username', $keyword);
            $this->db->or_like('email', $keyword);
            $this->db->or_like('no_hp', $keyword);
        $this->db->group_end();
        $this->db->order_by('nama_lengkap', 'ASC');
        return $this->db->get('users')->result();
    }

    // ═══════════════════════════════════════
    // RESET PASSWORD
    // ═══════════════════════════════════════

    public function reset_password_default($user_id) {
        // Reset ke password "password"
        $this->db->where('id', $user_id);
        return $this->db->update('users', [
            'password'   => password_hash('password', PASSWORD_DEFAULT),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
    }
}