<?php
//namespace app\libraries;
include APPPATH . 'libraries/CommonHelper.php';
include APPPATH . 'libraries/DateHelper.php';
include APPPATH . 'libraries/Userstamp.php';
use app\libraries\CommonHelper;
use app\libraries\DateHelper;
use app\libraries\Userstamp;

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class System_admin_model extends MY_Model
{
        protected $table = 'admin';

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

        public function validate(){
            $username = $this->security->xss_clean($this->input->post("username"));
            $password = $this->security->xss_clean($this->input->post('password'));
            $encrypted_password = sha1($password);
            
            $this->db->from($this->table);
            $this->db->where('username',$username);
            $this->db->where('password',$encrypted_password);
            return $this->db->get()->row_array();
        }

        public function systemLog($userId)
        {
            $this->db
                ->from($this->table)
                ->where('id', $userId)
                ->set('last_login_ip', CommonHelper::getClientIpEnv())
                ->set('last_login_time', DateHelper::getUNIXDate())
                ->set('login_count', 'login_count + 1', false)
                ->update();
        }

        public function create($params)
        {
    
            Userstamp::$timestamp = true;
            if (isset($params['created_by'])) {
                $params['created_at'] = $params['create_time'];
                unset($params['id']);
                unset($params['create_time']);
                $this->db->insert($this->table, $params);
            } else {
                Userstamp::$timestamp = true;
                $this->db->insert($this->table, Userstamp::create($params));
            }
    
            $params['id'] = $this->db->insert_id();
            return $params;
        }

        public function update($params, $id)
        {
            if (isset($params['updated_by'])) {
                $params['updated_at'] = $params['update_time'];
                unset($params['id']);
                unset($params['update_time']);
                $this->db->update($this->table, $params, ['id' => $id]);
            } else {
                Userstamp::$timestamp = true;
                $this->db->update($this->table, Userstamp::update($params), ['id' => $id]);
            }
    
            $params['id'] = $id;
            return $params;
        }
}
