<?php

namespace Hura8\Components\Customer\Model;

use Hura8\System\Model\AuthModel;


class CustomerAuthModel extends AuthModel
{

    private $tb_customer_login         = "tb_customer_login";
    private $tb_customer_access_code   = "tb_customer_access_code";
    private $tb_customer_login_log     = "tb_customer_login_log";

    public function __construct() {
        parent::__construct($this->tb_customer_login, $this->tb_customer_access_code);
    }


    public function getLoginListByIds(array $staff_ids) {
        if(!sizeof($staff_ids)) {
            return [];
        }

        list($parameterized_ids, $bind_types) = create_bind_sql_parameter_from_value_list($staff_ids, 'int');

        $bind_values = $staff_ids;

        $query = $this->db->runQuery(
            "SELECT `user_id`, `last_login_time`, `last_login_ip`, `last_login_device`, `last_login_browser` 
                    FROM ".$this->tb_customer_login."  
                    WHERE `user_id` IN (".$parameterized_ids.") ",
            $bind_types,
            $bind_values
        );

        $item_list = [];
        foreach ($this->db->fetchAll($query) as $item) {
            $item_list[$item['user_id']] = $item;
        }

        return $item_list;
    }


    public function getLoginLog(array $conditions = []) {
        $bind_types = [];
        $bind_values = [];

        $query = $this->db->runQuery(
            "SELECT *  FROM ".$this->tb_customer_login_log."  WHERE 1 ORDER BY `id` DESC LIMIT 100 ",
            $bind_types,
            $bind_values
        );

        return $this->db->fetchAll($query) ;
    }


    /**
     * @param $email
     * @param string $login_status ok or error
     * @param string $login_msg
     */
    public function logLogin($email, $login_status, $login_msg) {
        $this->db->insert(
            $this->tb_customer_login_log,
            [
                "email" => substr($email, 0, 45),
                "login_status" => $login_status,
                "login_msg" => substr($login_msg, 0, 45),
                "ip_address" => substr(USER_IP, 0, 45),
                "user_agent" => substr(USER_AGENT, 0, 99),
                "create_time" => CURRENT_TIME,
            ]
        );
    }

}
