<?php
session_start();

include('includes/ajax_check_login.php');

if( !isset($_POST['news_id']) || ( $static_uint_news_id = (int)$_POST['news_id'] ) <= 0 )
	exit(json_encode(array('ErrCode'=>-1, 'ErrMessage'=>'輸入資料不足', 'RedirectURL'=>'')));

require_once('includes/common.php');

require_once('includes/author.php');
$obj_class_author = new class_author();

if( !( $arr_news = $obj_class_author->get_news_by_news_id($static_uint_news_id) ) )
{
	$_SESSION['init_info'] = '指定的新聞不存在！';

	exit(json_encode(array('ErrCode'=>-1, 'ErrMessage'=>'', 'RedirectURL'=>'manage_news.php')));
}
else if( $obj_class_author->check_news_has_pictures($static_uint_news_id) )
	exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'新聞內尚有照片，無法刪除！', 'RedirectURL'=>'')));
else if( $obj_class_author->check_news_has_videos($static_uint_news_id) )
	exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'新聞內尚有影片，無法刪除！', 'RedirectURL'=>'')));

$str_dir_name = '../images/news/' . $arr_news[0]['NewsId'] . '/';
$str_img_file_name = '../images/news/' . $arr_news[0]['NewsId'] . '.jpg';

mysqli_query($obj_class_author->sql_connect, 'BEGIN;');

if( !$obj_class_author->delete_news($static_uint_news_id) )
{
	mysqli_query($obj_class_author->sql_connect, 'ROLLBACK;');
	mysqli_query($obj_class_author->sql_connect, 'COMMIT;');

	exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'新聞刪除失敗！', 'RedirectURL'=>'')));
}
else if( @file_exists($str_dir_name) && !@rmdir($str_dir_name) )
{
	mysqli_query($obj_class_author->sql_connect, 'ROLLBACK;');
	mysqli_query($obj_class_author->sql_connect, 'COMMIT;');

	exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'刪除圖片資料夾失敗！', 'RedirectURL'=>'')));
}
else if( @file_exists($str_img_file_name) && !@unlink($str_img_file_name) )
{
	mysqli_query($obj_class_author->sql_connect, 'ROLLBACK;');
	mysqli_query($obj_class_author->sql_connect, 'COMMIT;');

	exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'刪除標題圖片失敗！', 'RedirectURL'=>'')));
}

mysqli_query($obj_class_author->sql_connect, 'COMMIT;');

exit(json_encode(array('ErrCode'=>1, 'ErrMessage'=>'新聞刪除成功', 'RedirectURL'=>'')));
?>