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

class Admin_Controller extends MY_Controller
{
	public function __construct()
	{
		$this->requireAuth = true;
		$this->allowedRoles = array(1, 3); // Admin and staff
		parent::__construct();
		$this->layout = 'admin/_layout_main';

		// DB version check with light caching to avoid repeated queries.
		$this->load->model('admin_model');
		$verKey = 'db_version_current';
		$currentVersion = $this->cache->get($verKey);
		if ($currentVersion === FALSE) {
			$currentVersion = $this->admin_model->get_current_db_version();
			$this->cache->save($verKey, $currentVersion, 300);
		}
		$this->_current_version = $currentVersion;

		$currentUri = trim((string) uri_string(), '/');
		if ($currentUri === 'admin/auto_update' || strpos($currentUri, 'admin/auto_update/') === 0 || $currentUri === 'admin/auto_update_worker' || strpos($currentUri, 'admin/auto_update_worker/') === 0) {
			$this->enforceStaffRoutePermission();
			return;
		}

		if ($this->admin_model->is_db_upgrade_required($currentVersion) && !$this->input->post('auto_update', true)) {
			include_once(APPPATH . 'views/admin/settings/db_update_required.php');
			exit;
		}

		$this->enforceStaffRoutePermission();
	}

	// Admin specific methods can be added here

	private function enforceStaffRoutePermission(): void
	{
		$userType = (int) ($this->session->userdata('user_type') ?? 0);
		if ($userType !== 3) {
			return;
		}

		$currentUri = trim((string) uri_string(), '/');
		if ($currentUri === '') {
			return;
		}

		$alwaysAllowedPrefixes = array(
			'admin/common',
			'admin/dashboard/reset_cache',
			'admin/auto_update',
			'admin/auto_update_worker',
		);
		foreach ($alwaysAllowedPrefixes as $prefix) {
			if ($currentUri === $prefix || strpos($currentUri, $prefix . '/') === 0) {
				return;
			}
		}

		$this->load->model('Menu_model');
		$tree = $this->Menu_model->get_active_tree(false);
		$allowedPrefixes = array();
		$collect = function (array $items) use (&$collect, &$allowedPrefixes) {
			foreach ($items as $item) {
				$route = trim((string) ($item['route'] ?? ''), '/');
				if ($route !== '' && $route !== '#') {
					$segments = explode('/', $route);
					$prefix = count($segments) >= 2 ? ($segments[0] . '/' . $segments[1]) : $route;
					if (!in_array($prefix, $allowedPrefixes, true)) {
						$allowedPrefixes[] = $prefix;
					}
				}
				if (!empty($item['children']) && is_array($item['children'])) {
					$collect($item['children']);
				}
			}
		};
		$collect($tree);

		if (empty($allowedPrefixes)) {
			show_error('Unauthorized', 403);
		}

		foreach ($allowedPrefixes as $prefix) {
			if ($currentUri === $prefix || strpos($currentUri, $prefix . '/') === 0) {
				return;
			}
		}

		show_error('Unauthorized', 403);
	}


}
