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

class User_model extends CI_Model
{
    private $table = 'user';

    // ============================
    // AMBIL USER BERDASARKAN NIK_USER
    // ============================
    public function get_by_nik($nik_user)
    {
        return $this->db->get_where($this->table, ['nik_user' => $nik_user])->row();
    }

    // ============================
    // LOGIN: support plaintext, MD5, BCRYPT
    // ============================
    public function login($nik_user, $password_input)
    {
        // Ambil user berdasar NIK_USER
        $user = $this->get_by_nik($nik_user);

        if (!$user) {
            return false;
        }

        $password_db = $user->password;

        // 1. Cek password BCRYPT
        if (password_verify($password_input, $password_db)) {
            return $user;
        }

        // 2. Cek password MD5
        if ($password_db === md5($password_input)) {
            return $user;
        }

        // 3. Cek password plaintext
        if ($password_db === $password_input) {
            return $user;
        }

        // Kalau tidak cocok semua → gagal
        return false;
    }

    // ============================
    // UPDATE LAST ACTIVE
    // ============================
    public function set_last_active($nik_user)
    {
        return $this->db->update(
            $this->table,
            ['last_active' => date('Y-m-d H:i:s')],
            ['nik_user' => $nik_user]
        );
    }

public function get_user_with_unit($nik_user)
{
    return $this->db->select('user.*, unit.nama_unit, COALESCE(NULLIF(user.area, ""), unit.area, "") AS area', FALSE)
                    ->from('user')
                    ->join('unit', 'unit.id_unit = user.id_unit', 'left')
                    ->where('user.nik_user', $nik_user)
                    ->get()
                    ->row();
}



    
}
