<?php
session_start();

include('includes/ajax_check_login.php');

if( !isset($_POST['banner_id']) 
|| !isset($_FILES['img_file']) 
|| !isset($_POST['slogan']) 
|| !isset($_POST['url']) 
|| !isset($_POST['active']) 
|| ( $static_uint_banner_id = (int)$_POST['banner_id'] ) <= 0 
|| ( $static_str_slogan = trim(strip_tags($_POST['slogan'], '<br>')) ) == '' 
|| ( $static_uint_active = (int)$_POST['active'] ) < 0 
|| $static_uint_active > 1 )
	exit(json_encode(array('ErrCode'=>-1, 'ErrMessage'=>'輸入資料不足', 'RedirectURL'=>'')));
else
{
	$static_str_img_file = trim($_FILES['img_file']['tmp_name']);
	$static_str_url = trim($_POST['url']);
}

if( !$static_str_url || $static_str_url == '#' )
{
	$str_url = '';
	$uint_new_target = 0;
}
else
{
	$arr_matches = array();

	if( preg_match('/^(https?:\/\/[^\/]+\/)(.+)$/i', $static_str_url, $arr_matches) )
	{
		$str_url = strtolower($arr_matches[1]) . urlencode(rawurldecode($arr_matches[2]));

		if( false !== strpos($arr_matches[1], $_SERVER['HTTP_HOST']) )
			$uint_new_target = 0;
		else
			$uint_new_target = 1;
	}
	else
	{
		$str_url = $static_str_url;
		$uint_new_target = 1;
	}
}

require_once('includes/common.php');
require_once('includes/admin.php');

$obj_class_admin = new class_admin();

if( !( $arr_banner = $obj_class_admin->get_banner_by_banner_id($static_uint_banner_id) ) )
	exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'所選擇的廣告不存在！', 'RedirectURL'=>'')));

if( $static_str_img_file )
{
	if( ( $arr_image_info = getimagesize($static_str_img_file) ) && $arr_image_info[2] == 2 && ( !$static_uint_news_cate_id && $arr_image_info[0] == INDEX_BANNER_WIDTH && $arr_image_info[1] == INDEX_BANNER_HEIGHT || $static_uint_news_cate_id && $arr_image_info[0] == NEWS_BANNER_WIDTH && $arr_image_info[1] == NEWS_BANNER_HEIGHT ) )
	{
		$str_file_name = '../images/banners/' . $static_uint_banner_id . '.jpg';

		if( file_exists($str_file_name) )
			unlink($str_file_name);

		if( !move_uploaded_file($static_str_img_file, $str_file_name) )
			exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'廣告圖檔上傳失敗！', 'RedirectURL'=>'')));
	}
	else
		exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'廣告圖檔格式不正確！', 'RedirectURL'=>'')));
}

if( !$obj_class_admin->update_banner($static_uint_banner_id, $static_str_slogan, $str_url, $uint_new_target, $static_uint_active) )
	exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'編輯廣告失敗！', 'RedirectURL'=>'')));
else
	exit(json_encode(array('ErrCode'=>1, 'ErrMessage'=>'編輯廣告成功！', 'RedirectURL'=>'')));
?>