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

class Adm extends CI_Controller {

	function __construct(){
		parent::__construct();
		$this->load->helper('string');
		$this->title = info()['title'];
	}

	function index(){
		$data['title'] = 'Administrator &rsaquo; Log In | '.$this->title;
		$data['description'] = 'Aplikasi POS Percetakan';
		$data['keywords'] = 'point of sale, pos percetakan, aplikasi percetakan';
		$data['email'] = '';
		$data['list'] = [];

		if(!empty($this->input->get('email'))){
			$data['email'] = decrypt_url($this->input->get('email'));
			$data['list'] = $this->model_app->pilih_where('email','tb_users',['email'=>$data['email']]);
		}

		if (isset($_POST['submit'])){

			$cek_info   = cek_info();

			$email_user = $this->input->post('email_user');
			$password   = $this->input->post('pass_user');
			$cek        = $this->model_app->cek_user($email_user);
			$total      = $cek->num_rows();

			if ($total > 0){
				$sid_baru = session_id();
				$row = $cek->row_array();
				$hash = $row['password'];

				if (password_verify($password, $hash)) {

					$this->session->set_userdata(array(
						'idu'        => $row['id_user'],
						'emailu'     => $row['email'],
						'nama'       => $row['nama_lengkap'],
						'idparent'   => $row['parent'],
						'id_lv'      => $row['id_level'],
						'idlv'       => $row['idlevel'],
						'level'      => $row['level'],
						'id_session' => $row['id_session'],
						'type_akses' => $row['type_akses'],
						'ids'        => $sid_baru,
						'sesi'       => $sid_baru
					));

					$this->model_app->update('tb_users', array("sesi_login"=>$sid_baru), array('id_user'=>$this->session->idu));

					// ==============================
					// HISTORY LOGIN + ONLINE TRACKING (STABIL)
					// key utama: device_id (cookie per perangkat)
					// ==============================
					$now = date('Y-m-d H:i:s');

					$cek_info = cek_info();
					$ip      = substr((string)$cek_info['ip'], 0, 15);
					$os      = substr((string)$cek_info['os'], 0, 50);
					$browser = substr((string)$cek_info['browser'], 0, 50);

					// device id permanen per perangkat (cookie)
					$device_id = $this->input->cookie('pg_device_id', true);
					if (empty($device_id)) {
					    // format: dev_ + random
					    $device_id = 'dev_' . bin2hex(random_bytes(10));
					    // set cookie 1 tahun
					    setcookie('pg_device_id', $device_id, time() + (86400 * 365), "/", "", false, true);
					}

					// cari berdasarkan device_id dulu
					$q = $this->db->get_where('user_agent', ['device_id' => $device_id], 1);

					if ($q->num_rows() > 0) {
					    $this->db->set('counter', 'counter+1', false);
					    $this->db->set('update_date', $now);       // last login
					    $this->db->set('last_activity', $now);    // last online activity
					    $this->db->set('id_user', (int)$this->session->idu);
					    $this->db->set('ip', $ip);
					    $this->db->set('os', $os);
					    $this->db->set('browser', $browser);
					    $this->db->where('device_id', $device_id);
					    $this->db->update('user_agent');
					} else {
					    $this->db->insert('user_agent', [
					        'device_id'     => $device_id,
					        'id_user'       => (int)$this->session->idu,
					        'ip'            => $ip,
					        'os'            => $os,
					        'browser'       => $browser,
					        'counter'       => 1,
					        'create_date'   => $now,
					        'update_date'   => $now,
					        'last_activity' => $now,
					    ]);
					}


					if (in_array(strtolower(trim($row['level'])), ['kasir', 'desain'], true)) {
						redirect('penjualan/order');
					} else {
						redirect('home');
					}

				} else {
					echo $this->session->set_flashdata('message', '<div class="alert alert-danger"><center>Username atau Password Salah!!</center></div>');
					$data['title'] = 'Username atau Password salah!';
					$this->load->view('element/login', $data);
				}

			} else {
				echo $this->session->set_flashdata('message', '<div class="alert alert-danger"><center>Username atau Password Salah!!</center></div>');
				$data['title'] = 'username salah atau akun anda sedang diblokir';
				$this->load->view('element/login', $data);
			}

		} else {
			if ($this->session->level!=''){
				redirect('home');
			} else {
				$this->load->view('element/login', $data);
			}
		}
	}
}
