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

class History extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->perPage = 10;
		$this->title = info()['title'];
	}

	public function index($id=null)
	{
		cek_menu_akses();

		$data['title'] ="History | ".$this->title;

		$conditions['returnType'] = 'count';
		$totalRec = $this->model_data->getHistory($conditions);

		// ===== Ringkasan Online/Offline (tanpa filter) =====
		$condOnline = array('returnType' => 'count', 'search' => array('onlineOnly' => 1));
		$onlineRec  = (int) $this->model_data->getHistory($condOnline);
		$offlineRec = max(0, (int)$totalRec - $onlineRec);

		$data['onlineRec']  = $onlineRec;
		$data['offlineRec'] = $offlineRec;


		$config['target']      = '#dataListHistory';
		$config['base_url']    = base_url('main/ajaxHistory');
		$config['total_rows']  = $totalRec;
		$config['per_page']    = $this->perPage;
		$config['link_func']   = 'searchFilterHistory';

		$this->ajax_pagination->initialize($config);

		$conditions = array('limit' => $this->perPage);
		$data['posts'] = $this->model_data->getHistory($conditions);

		$this->template->load('main/themes','main/history',$data);
	}

	function ajaxHistory(){
		cek_session_login();

		$page = $this->input->post('page');
		$offset = (!$page) ? 0 : $page;

		$limits = $this->input->post('limits');
		$limit = (!empty($limits)) ? $limits : $this->perPage;

		$keywords = $this->input->post('keywords');
		$sortBy   = $this->input->post('sortBy');
		$onlineOnly = $this->input->post('onlineOnly'); // 1/0


		if(!empty($keywords)){
			$conditions['search']['keywords'] = $keywords;
		}
		if(!empty($sortBy)){
			$conditions['search']['sortBy'] = $sortBy;
		}
		if(!empty($limits)){
			$conditions['search']['limits'] = $limits;
		}

		if (!empty($onlineOnly) && $onlineOnly == '1') {
		    $conditions['search']['onlineOnly'] = 1;
		}


		// =============================
		// BUILD base search (untuk ringkasan: keyword saja)
		// =============================
		$baseSearch = array();
		if(!empty($keywords)){
		  $baseSearch['keywords'] = $keywords;
		}

		// ===== Ringkasan: total perangkat (dengan keyword) =====
		$condAll = array('returnType' => 'count');
		if(!empty($baseSearch)) $condAll['search'] = $baseSearch;
		$totalAll = (int) $this->model_data->getHistory($condAll);

		// ===== Ringkasan: online perangkat (dengan keyword) =====
		$condOn = array('returnType' => 'count', 'search' => $baseSearch);
		$condOn['search']['onlineOnly'] = 1;
		$onlineAll  = (int) $this->model_data->getHistory($condOn);
		$offlineAll = max(0, $totalAll - $onlineAll);

		// ===== Count untuk pagination (sesuai filter onlineOnly) =====
		$listCond = array();
		if(!empty($baseSearch)) $listCond['search'] = $baseSearch;
		if(!empty($onlineOnly) && $onlineOnly=='1'){
		  $listCond['search']['onlineOnly'] = 1; // pagination mengikuti filter
		}

		$listCond['returnType'] = 'count';
		$totalRec = (int) $this->model_data->getHistory($listCond);

		// config pagination tetap pakai totalRec (sesuai tabel yg sedang ditampilkan)
		$config['target']      = '#dataListHistory';
		$config['base_url']    = base_url('history/ajaxHistory');
		$config['total_rows']  = $totalRec;
		$config['per_page']    = $limit;
		$config['link_func']   = 'searchFilterHistory';

		$this->ajax_pagination->initialize($config);

		// ambil data list (sesuai filter)
		$listCond['start'] = $offset;
		$listCond['limit'] = $limit;
		unset($listCond['returnType']);

		$data['start']      = $offset;
		$data['posts']      = $this->model_data->getHistory($listCond);

		// kirim ringkasan (real-time)
		$data['onlineRec']  = $onlineAll;
		$data['offlineRec'] = $offlineAll;


		$data['start'] = $offset;
		$data['posts'] = $this->model_data->getHistory($conditions);

		$this->load->view('main/ajax-history', $data, false);
	}

	// ✅ endpoint untuk update "last_activity" (online tracking)
	public function ping()
	{
		cek_session_login();

		$cek_info = cek_info();
		$now = date('Y-m-d H:i:s');

		$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)) {
		    $device_id = 'dev_' . bin2hex(random_bytes(10));
		    setcookie('pg_device_id', $device_id, time() + (86400 * 365), "/", "", false, true);
		}

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

		if ($q->num_rows() > 0) {
		    $this->db->set('last_activity', $now);
		    $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,
		    ]);
		}


		$this->output
			->set_content_type('application/json')
			->set_output(json_encode(['status'=>200]));
	}

	function resethistory()
	{
		cek_session_login(1);
		database_demo('Reset');

		$data = array();
		if($this->db->truncate('user_agent')===TRUE){
			$data = array('status'=>200);
		} else {
			$data = array('status'=>400);
		}
		echo json_encode($data);
	}
}
