<?php

require_once __DIR__ . '/core.php';

if ($con->request->isAjax()) {
    $action = $con->request->post('action');
    switch ($action) {
        case 'list':
        	$current = json_decode(file_get_contents(CONF.'/template.json'), true)['template'];
        	$templates = [];
        	foreach (scandir(PATH.'/templates') as $dir) {
        		if (strpos($dir, '.') === false && is_dir(PATH.'/templates/'.$dir)) {
        			$templates[] = [
        				'name' => $dir,
				        'image' => '<img src="'.loadImage('templates/'.$dir.'/controllers/preview.jpg', $hel).'" alt="'.$dir.'">',
				        'current' => $current == $dir ? '✔' : '✘'
			        ];
		        }
	        }
	        $data = [
		        'msg'   => '',
		        'code'  => 0,
		        'count' => count($templates),
		        'data'  => $templates
	        ];
            $con->json($data);
            break;
        case 'use':
        	$name = $con->request->post('unique');
	        $template = json_decode(file_get_contents(CONF.'/template.json'), true);
	        if ($name == $template['template']) {
		        $con->json(['code' => false, 'err' => '模板未更改']);
	        } else {
		        $tpl_dir = PATH.'/templates/'.$name;
		        if (is_dir($tpl_dir)) {
			        if (is_file($tpl_dir.'/controllers/IndexController.php')) {
				        if (copy($tpl_dir.'/controllers/IndexController.php', PATH.'/controllers/IndexController.php')) {
					        $con->json(['code' => true]);
					        $template['template'] = $name;
					        file_put_contents(CONF.'/template.json', json_encode($template));
			        } else {
					        $con->json(['code' => false, 'err' => '模板应用失败']);
				        }
			        } else {
				        $con->json(['code' => false, 'err' => '模板核心文件缺失，请联系系统管理员']);
			        }
		        } else {
			        $con->json(['code' => false, 'err' => '模板不存在']);
		        }

	        }
            break;
        default:break;
    }
} else {
    $con->render('tpl', ['host' => $hel->url(), 'path' => $hel->path(), 'crumb' => $breadcrumb]);
}