<?php
if(!defined('__KIMS__')) exit;

checkAdmin(0);

$_switchset = array('start','top','head','foot','end');
$switch_folder = (string)($switch_folder ?? '');
$switch = (string)($switch ?? '');

if (!in_array($switch_folder,$_switchset,true) || !preg_match('/^[A-Za-z0-9_-]+@?$/',$switch))
{
	getLink($g['s'].'/?r='.$r.'&m=admin&module=admin&front=switch','parent.','정상적인 접근이 아닙니다.','');
}

$_sw1 = $g['path_switch'].$switch_folder;
$_source = $_sw1.'/'.$switch;
$_enabled = substr($switch,-1) === '@' ? substr($switch,0,-1) : $switch.'@';
$_target = $_sw1.'/'.$_enabled;

if (!is_file($_source.'/main.php') || file_exists($_target) || !@rename($_source,$_target))
{
	getLink($g['s'].'/?r='.$r.'&m=admin&module=admin&front=switch','parent.','스위치 상태를 변경하지 못했습니다. 폴더 권한을 확인해 주세요.','');
}

$_contents = "<?php\n";
foreach ($_switchset as $_key)
{
	foreach ((array)($d['switch'][$_key] ?? array()) as $_val)
	{
		if ($_key === $switch_folder && $_val === $switch) $_val = $_enabled;
		$_contents .= "\$d['switch']['".$_key."'][] = ".var_export(trim($_val),true).";\n";
	}
}
$_contents .= "?>";

$_ufile = $g['path_var'].'switch.var.php';
$_tmpfile = $_ufile.'.tmp.'.getmypid();
$_written = @file_put_contents($_tmpfile,$_contents,LOCK_EX);
if ($_written === false || !@rename($_tmpfile,$_ufile))
{
	@unlink($_tmpfile);
	@rename($_target,$_source);
	getLink($g['s'].'/?r='.$r.'&m=admin&module=admin&front=switch','parent.','스위치 설정을 저장하지 못했습니다.','');
}
@chmod($_ufile,0664);

$alert = '['.getFolderName($_target).'] 스위치가 '.(substr($_enabled,-1) === '@'?'꺼졌습니다.':'켜졌습니다.');
if (($reload ?? '') === 'Y') getLink('reload','parent.',$alert,'');
else getLink($g['s'].'/?r='.$r.'&m=admin&module=admin&front=switch','parent.',$alert,'');
?>
