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

class Cdnadmin extends CI_Controller
{
	private $menuMap = [
		'pesanan' => ['label' => 'Pesanan', 'path' => 'ngadimin/pesanan'],
		'file-desain' => ['label' => 'File Desain', 'path' => 'ngadimin/filedesain'],
		'voucher' => ['label' => 'Voucher', 'path' => 'ngadimin/voucher'],
		'slider' => ['label' => 'Slider', 'path' => 'ngadimin/slider'],
		'broadcast' => ['label' => 'Broadcast', 'path' => 'ngadimin/broadcast'],
		'laporan-produk' => ['label' => 'Laporan Produk', 'path' => 'ngadimin/laporanproduk'],
		'produk' => ['label' => 'Produk', 'path' => 'ngadimin/produk'],
		'kategori' => ['label' => 'Kategori', 'path' => 'ngadimin/kategori'],
		'topup-saldo' => ['label' => 'Topup Saldo', 'path' => 'ngadimin/topupsaldo'],
		'penarikan-saldo' => ['label' => 'Penarikan Saldo', 'path' => 'ngadimin/tariksaldo'],
		'testimoni' => ['label' => 'Testimoni', 'path' => 'ngadimin/testimoni'],
		'lokasi-gudang' => ['label' => 'Lokasi Gudang', 'path' => 'gudang'],
		'custom-kurir' => ['label' => 'Custom Kurir', 'path' => 'ngadimin/paketkurir'],
		'pengaturan' => ['label' => 'Pengaturan', 'path' => 'ngadimin/pengaturan'],
	];

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

	public function index($key = 'pesanan')
	{
		if (!isset($this->menuMap[$key])) {
			show_404();
			return;
		}

		$secret = (string) $this->config->item('cdn_admin_sso_secret');
		$user = (string) $this->config->item('cdn_admin_sso_user');
		$baseUrl = (string) $this->config->item('cdn_admin_base_url');
		$next = $this->menuMap[$key]['path'];
		if ($secret === '' || $user === '' || $baseUrl === '') {
			show_error('Konfigurasi CDN admin belum lengkap.');
			return;
		}

		$baseUrl = rtrim($baseUrl, '/') . '/';
		$ts = time();
		if (function_exists('random_bytes')) {
			$nonce = bin2hex(random_bytes(8));
		} else {
			$nonce = bin2hex(openssl_random_pseudo_bytes(8));
		}
		$payload = $user . '|' . $next . '|' . $ts . '|' . $nonce;
		$sig = hash_hmac('sha256', $payload, $secret);

		$iframeUrl = $baseUrl . 'ngadimin/sso'
			. '?user=' . rawurlencode($user)
			. '&next=' . rawurlencode($next)
			. '&ts=' . $ts
			. '&nonce=' . $nonce
			. '&sig=' . $sig;

		// Beberapa halaman CDN mengirim CSP "frame-ancestors 'self'",
		// sehingga tidak bisa ditampilkan di iframe domain ini.
		// Default: redirect langsung agar halaman tetap terbuka tanpa error iframe.
		$mode = strtolower((string) $this->input->get('mode', true));
		if ($mode !== 'embed') {
			redirect($iframeUrl, 'location', 302);
			return;
		}

		$data = [
			'title' => 'Via Admin CDN - ' . $this->menuMap[$key]['label'],
			'iframe_url' => $iframeUrl,
			'cdn_label' => $this->menuMap[$key]['label'],
		];

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