<?php 

// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

require_once 'library/top_application.php';
require_once 'library/logged.php';

if (isset($_GET['action'])) {
  $action=$_GET['action'];
}
if (isset($_GET['id'])) {
  $id=$_GET['id'];
}

if ($action != 'add' && $action != 'edit'){
	$action='add';
}
//權限 
$sql_right = mysql_query('SELECT `manage_gallery` FROM `'.TBL_USER.'` WHERE `uid` = '.$_SESSION['Logged_Uid']);
$row_right = mysql_fetch_assoc($sql_right);

if($row_right['manage_gallery'] != 1){
	header("Location: listUser.php");
}

$sql_lang = mysql_query('SELECT `first_language` FROM `general_setting` WHERE `id` = 1');
$row_lang = mysql_fetch_assoc($sql_lang);

if ($row_lang['first_language'] == 1){
	//eng
	$lang_table = 'en_table';
	$must_subject = 'ep_subject';
	$lang_btn = 'btn_lang_switch_en';
} elseif ($row_lang['first_language'] == 2){
	//tc
	$lang_table = 'tc_table';
	$must_subject = 'cp_subject';
	$lang_btn = 'btn_lang_switch_tc';
} elseif ($row_lang['first_language'] == 3){
	//sc
	$lang_table = 'sc_table';
	$must_subject = 'sp_subject';
	$lang_btn = 'btn_lang_switch_sc';
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "fHtmlEditor")){
	$ep_date = isDate(trim($_POST['ep_date']));
	$ep_web = isNumber(trim($_POST['ep_web']));
	$cp_subject = txt_only($_POST['cp_subject']);
	$ep_subject = txt_only($_POST['ep_subject']);
	$sp_subject = txt_only($_POST['sp_subject']);
	$cp_brief = htmlPurify($_POST['cp_brief']);
	$ep_brief = htmlPurify($_POST['ep_brief']);
	$sp_brief = htmlPurify($_POST['sp_brief']);
	
	if(!get_magic_quotes_gpc()){ 
		$cp_subject = mysql_real_escape_string($cp_subject);
		$ep_subject = mysql_real_escape_string($ep_subject);
		$sp_subject = mysql_real_escape_string($sp_subject);
		$cp_brief = mysql_real_escape_string($cp_brief);
		$ep_brief = mysql_real_escape_string($ep_brief);
		$sp_brief = mysql_real_escape_string($sp_brief);
	}
	$sql_rank = mysql_query('SELECT `rank` FROM `album` ORDER BY `rank` DESC LIMIT 0, 1');
	$row_rank = mysql_fetch_assoc($sql_rank);
	$insert_rank = $row_rank['rank']+1;


	//added upload file
	//2019-10-08
	$target_dir = "../upload/album_images/";
	$str = md5(uniqid(mt_rand(), true));  
    $uuid  = substr($str,0,8);
	$target_file = $target_dir .$uuid. basename($_FILES["xfile"]["name"]);
	$uploadOk = 1;
	$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
	// Check if image file is a actual image or fake image
	// if(isset($_POST["submit"])) {
	//     $check = getimagesize($_FILES["xfile"]["tmp_name"]);
	//     if($check !== false) {
	//         echo "File is an image - " . $check["mime"] . ".";
	//         $uploadOk = 1;
	//     } else {
	//         echo "File is not an image.";
	//         $uploadOk = 0;
	//     }
	// // }
	// Check if file already exists
	if (file_exists($target_file)) {
	    echo "Sorry, file already exists.";
	    $uploadOk = 0;
	}
	// Check file size
	// if ($_FILES["xfile"]["size"] > 500000) {
	if ($_FILES["xfile"]["size"] > 5000000) {
	    echo "Sorry, your file is too large.";
	    $uploadOk = 0;
	}
	// Allow certain file formats
	if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
	&& $imageFileType != "gif" ) {
	    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
	    $uploadOk = 0;
	}
	// Check if $uploadOk is set to 0 by an error
	if ($uploadOk == 0) {
	    echo "Sorry, your file was not uploaded.";
	// if everything is ok, try to upload file
	} else {
		$file_name2="moveuploadfile";
	    if (move_uploaded_file($_FILES["xfile"]["tmp_name"], $target_file)) {
	        // echo "The file ". basename( $_FILES["xfile"]["name"]). " has been uploaded.";
	        $file_name2= "The file ". basename( $_FILES["xfile"]["name"]). " has been uploaded.";
	    } else {
	        echo "Sorry, there was an error uploading your file.";
	        // $file_name2= "Sorry, there was an error uploading your file.";
	    }
	}

	// $file_name2=$_FILES["xfile"]["size"];
	$file_name2=$uuid.$_FILES["xfile"]["name"];
	//ended upload file


	
	mysql_query("INSERT INTO `album` (ep_date, ep_web, cp_subject, ep_subject, sp_subject, cp_brief, ep_brief, sp_brief, last_update, rank,ep_pic) VALUES ('$ep_date', '$ep_web', '$cp_subject', '$ep_subject', '$sp_subject', '$cp_brief', '$ep_brief', '$sp_brief', NOW(), '$insert_rank','$file_name2')", $connePaper) or die(mysql_error());
	header("Location: close_iframe.html");
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "fHtmlEditor")){
	$ep_date = isDate(trim($_POST['ep_date']));
	$ep_web = isNumber(trim($_POST['ep_web']));
	$cp_subject = txt_only($_POST['cp_subject']);
	$ep_subject = txt_only($_POST['ep_subject']);
	$sp_subject = txt_only($_POST['sp_subject']);
	$cp_brief = htmlPurify($_POST['cp_brief']);
	$ep_brief = htmlPurify($_POST['ep_brief']);
	$sp_brief = htmlPurify($_POST['sp_brief']);
	$album_id = isNumber(trim($_POST['album_id']));
	
	if(!get_magic_quotes_gpc()){ 
		$cp_subject = mysql_real_escape_string($cp_subject);
		$ep_subject = mysql_real_escape_string($ep_subject);
		$sp_subject = mysql_real_escape_string($sp_subject);
		$cp_brief = mysql_real_escape_string($cp_brief);
		$ep_brief = mysql_real_escape_string($ep_brief);
		$sp_brief = mysql_real_escape_string($sp_brief);
	}

	//handle upload file
	$uploadfilename="";
	$originalfilename=$_POST['originalfilename'];
	$uploadfilename=$originalfilename;
	$newfilename=basename($_FILES["xfile"]["name"]);
	if(!empty($newfilename)){
			$target_dir = "../upload/album_images/";
			unlink($target_dir.$originalfilename);
			$str = md5(uniqid(mt_rand(), true));  
		    $uuid  = substr($str,0,8);
			$target_file = $target_dir .$uuid. basename($_FILES["xfile"]["name"]);
			$uploadOk = 1;
			$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
			// Check if image file is a actual image or fake image
			// if(isset($_POST["submit"])) {
			//     $check = getimagesize($_FILES["xfile"]["tmp_name"]);
			//     if($check !== false) {
			//         echo "File is an image - " . $check["mime"] . ".";
			//         $uploadOk = 1;
			//     } else {
			//         echo "File is not an image.";
			//         $uploadOk = 0;
			//     }
			// // }
			// Check if file already exists
			if (file_exists($target_file)) {
			    echo "Sorry, file already exists.";
			    $uploadOk = 0;
			}
			// Check file size
			// if ($_FILES["xfile"]["size"] > 500000) {
			if ($_FILES["xfile"]["size"] > 5000000) {
			    echo "Sorry, your file is too large.";
			    $uploadOk = 0;
			}
			// Allow certain file formats
			if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
			&& $imageFileType != "gif" ) {
			    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
			    $uploadOk = 0;
			}
			// Check if $uploadOk is set to 0 by an error
			if ($uploadOk == 0) {
			    echo "Sorry, your file was not uploaded.";
			// if everything is ok, try to upload file
			} else {
				$file_name2="moveuploadfile";
			    if (move_uploaded_file($_FILES["xfile"]["tmp_name"], $target_file)) {
			        // echo "The file ". basename( $_FILES["xfile"]["name"]). " has been uploaded.";
			        $file_name2= "The file ". basename( $_FILES["xfile"]["name"]). " has been uploaded.";
			    } else {
			        // echo "Sorry, there was an error uploading your file.";
			        $file_name2= "Sorry, there was an error uploading your file.";
			    }
			}

			// $file_name2=$_FILES["xfile"]["size"];
			$file_name2=$uuid.$_FILES["xfile"]["name"];
			$uploadfilename=$file_name2;
	}//if(!empty($newfilename)){
	//end handle upload file

	mysql_query("UPDATE `album` SET `ep_web` = '$ep_web', `ep_date` = '$ep_date', `cp_subject` = '$cp_subject', `ep_subject` = '$ep_subject', `sp_subject` = '$sp_subject', `cp_brief` = '$cp_brief', `ep_brief` = '$ep_brief', `sp_brief` = '$sp_brief', `last_update` = NOW(), `ep_pic`='$uploadfilename' WHERE `album_id` = '$album_id'", $connePaper) or die(mysql_error());
	header("Location: close_iframe.html");
}

$sql_size = mysql_query('SELECT `album_w`, `album_h` FROM `general_setting` WHERE `id` = 1');
$row_size = mysql_fetch_assoc($sql_size);
if(!$row_size['album_w']){
	$pic_w = DEFAULT_ALBUM_W;
} else {
	$pic_w = $row_size['album_w'];
}
if(!$row_size['album_h']){
	$pic_h = DEFAULT_ALBUM_H;
} else {
	$pic_h = $row_size['album_h'];
}


//list all section
$sql_section = mysql_query('SELECT * FROM `section` WHERE `type` = 3 AND `show` = 1 ORDER BY `rank` ASC')or die(mysql_error());
$row_section = mysql_fetch_assoc($sql_section);

if ($action == 'edit'){
	$sql = mysql_query("SELECT * FROM `album` WHERE `album_id` = ".$id);
	$row = mysql_fetch_assoc($sql);
	$web = $row['ep_web'];
} else {
	if (isset($_GET['web'])) {
	  $web=$_GET['web'];
	} else{
		$web=1;
	}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Artech Creative</title>

<link href="css/css_admin.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui-min.js"></script>
<script type="text/javascript" src="../js/tinybox.js"></script>
<!--[if IE]>
    <script src="../js/html5.js"></script>
<![endif]--> 
<link href="css/anytime.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../js2/anytime.js"></script>
<!-- <script type="text/javascript" src="../js2/droparea.js"></script> -->
<script type="text/javascript" src="../js2/BlobBuilder.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>

<script type="text/javascript">
$(document).ready(function(){
  $('.lang_content_table').css('display', 'none');
  $('#<?php echo $lang_table;?>').css('display', 'block');
  $('#<?php echo $lang_btn;?>').addClass('selected');
  $("#ep_date").AnyTime_picker(
    { format: "%Y-%m-%d", labelTitle: "日期"} );
	
	$('#btn_lang_switch_content a').click(function(){
		$('#btn_lang_switch_content a').removeClass('selected');
		$(this).addClass('selected');
	})
	
	// Calling jQuery "droparea" plugin
	$('.droparea').droparea({
		'instructions': 'drop a file or click to here to upload photo',
		'init' : function(result){
		//console.log('custom init',result);
		},
		'start' : function($this){
		$this.area.find('.error').remove(); 
		
		},
		'error' : function(result, input, area){
		$('<div class="error">').html(result.error).prependTo(area); 
		return 0;
		//console.log('custom error',result.error);
		},
		'complete' : function($this, file){
		console.log('this',$this);
		if((/image/i).test(file.type)){
			var del_img = $this.area.find('img').attr('src');
			if(del_img){
				$.ajax({
					type: "POST",
					url: "ajax/instant_photo_function.php",
					data: {"del_path" : del_img},
					cache: false
				});
			}
			$this.area.find('img').remove();
			//area.data('value',result.filename);
			$this.area.append($('<img>',{
				//'src': $this.result.path + $this.result.filename + '?' + Math.random()					
				'src': $this.result.filename .replace("../../","../"),
				'width': 150,
				'id': 'cur_thumb'
			}));
			<?php if($action=='add'){?>
			var image_name = $this.result.filename.replace("../../upload/album_images/","");
			var ep_web = $('#ep_web').val();
			$.ajax({
				type: "POST",
				url: "ajax/instant_photo_function.php",
				data: {"new_album_image" : image_name, "album_type" : ep_web},
				cache: false,
				success: function(html){
					$('body').html(html);
				}
			});
			<?php }?>
			
			<?php if($action=='edit'){?>
			var del_img = $('#cur_thumb').attr('src');
			if(del_img){
				$.ajax({
					type: "POST",
					url: "ajax/instant_photo_function.php",
					data: {"del_path" : del_img},
					cache: false
				});
			}
			var image_name = $this.result.filename.replace("../../upload/album_images/","");
			var ep_web = $('#ep_web').val();
			$.ajax({
				type: "POST",
				url: "ajax/instant_photo_function.php",
				data: {"updates_album_image" : image_name, "album_type" : ep_web, "album_id" : <?php echo $id;?>},
				cache: false,
				success: function(html){
					$('#upload_success').html('<strong style="color:red">Photo updated</strong>,  Click or drag photo a photo on the image to re-upload the image.');
					$('#upload_success').css('display', 'block');
				}
			});
			$('#cur_image, #cur_image_2').remove();
			<?php }?>
		} 
		//console.log('custom complete',result);
		}
	});
})

function switch_lang(id){
	$('.lang_content_table:not(#'+id+'_table)').css('display', 'none');
	$('#'+id+'_table').css('display', 'block');
}


function OnFormSubmit(){
	var must_subject = $.trim($('#<?php echo $must_subject;?>').val());
	if (!must_subject){
		$('.er_msg').css('display', 'block');
		
		$('.lang_content_table').css('display', 'none')
		$('#<?php echo $lang_table;?>').css('display', 'block')
		$('#btn_lang_switch_content a').removeClass('selected');
		$('#<?php echo $lang_btn;?>').addClass('selected');
		$('#<?php echo $must_subject;?>').focus();
	} else {
	  if(confirm("This Document is about to be submitted\nAre you sure you have finished editing?")){
		document.fHtmlEditor.submit();
	  }
	}
}
</script>

</head>
<body style="background:#fff">
<table width="100%" border="0" cellpadding="0" cellspacing="0" style="padding:20px;" >
  <tr>
    <td><h2><? if ($action=='add'){ echo '新增新聞';} else { echo '修改新聞';}?></h2></td>
  </tr>
  <tr>
    <td><hr></td>
  </tr>
  <tr>
    <td><table width="100%" border="0" cellpadding="4" cellspacing="0" >
      <tr>
        <td>
          <form name="fHtmlEditor" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" >
            <table width="100%"  border="0" cellpadding="2" cellspacing="1" class="content">
                <tr>
                <td width="120">Date: </td>
                <td><input name="ep_date" type="text" id="ep_date" value="<? if ($action=='add'){ echo date('Y-m-d');} else {echo $row['ep_date'];}?>"></td>
              </tr>
              <tr>
              	<td>Album Type</td>
                  <td>
                  <select name="ep_web" id="ep_web" style="width:144px">
                  	<?php do {?>
                   	<option value="<?php echo $row_section['section_id'];?>" <?php if ($web== $row_section['section_id']){echo 'selected';}?>><?php echo $row_section['ep_name']?></option>
                    <?php } while ($row_section = mysql_fetch_assoc($sql_section));?>
                  </select>
                  
                  </td>
              </tr>
              <?php if($action=='add'){?>
              <tr>
              <td width="120">Album Thumb:<br>
              (<?php echo $pic_w;?>px * <?php echo $pic_h;?>px)</td>
                  <td>
                  	<!-- <input type="file" class="droparea spot" name="xfile" data-post="upload/drop_Photo_album.php" data-width="<?php echo $pic_w;?>" data-height="<?php echo $pic_h;?>" data-crop="true" data-canvas="true"/> -->
                 <input type="file" class="droparea spot" name="xfile"  data-width="<?php echo $pic_w;?>" data-height="<?php echo $pic_h;?>" data-crop="true" data-canvas="true"/>
                 <!-- <input type="file" name="xfile" id="xfile"> -->
                  </td>
              </tr>
				<tr>
              <td width="120"></td>
                  <td><div id="upload_success" style="display:none"><strong style="color:red">Photo updated</strong>,  Click or drag photo a photo on the image to re-upload the image.</div></td>
              </tr>
			  <?php
			  } elseif($action=='edit'){ ?>
              <tr >
              <td width="120" height="144">Current album Thumb:<br>
              (<?php echo $pic_w;?>px * <?php echo $pic_h;?>px)</td>
              <td>
              <table width="100%" border="0" cellpadding="0" cellspacing="0" class="content">
                <tr>
                  <td width="180" id="cur_image"><img src="../upload/album_images/<?=$row['ep_pic']?>" id="cur_thumb" width="150"/>
                  <td width="120" id="cur_image_2">Change album Thumb:<br>
              (<?php echo $pic_w;?>px * <?php echo $pic_h;?>px)</td>
                  <td>
                  	<input type="file" class="droparea spot" name="xfile" data-post="upload/drop_Photo_album.php" data-width="<?php echo $pic_w;?>" data-height="<?php echo $pic_h;?>" data-crop="true" data-canvas="true"/>

                  	<!-- <input type="file" class="droparea spot" name="xfile"  data-width="<?php echo $pic_w;?>" data-height="<?php echo $pic_h;?>" data-crop="true" data-canvas="true"/> -->
                  	<input type="hidden" name="originalfilename" value="<?php echo $row['ep_pic'];?>" >
                  </td>
                </tr>
              </table></td>
              </tr>
			  <tr>
              <td width="120"></td>
                  <td><div id="upload_success" style="display:none"><strong style="color:red">Photo updated</strong>,  Click or drag photo a photo on the image to re-upload the image.</div></td>
              </tr><? }?>
              <tr>
                <td width="120" valign="top">選擇修改語言:</td>
                <td>
                  <div id="btn_lang_switch_content"><a href="javascript:switch_lang('en')" id="btn_lang_switch_en">ENG</a> | <a href="javascript:switch_lang('tc')" id="btn_lang_switch_tc">繁</a> | <!--a href="javascript:switch_lang('sc')" id="btn_lang_switch_sc">簡</a--></div><span class="er_msg">必須輸入標題</span></td>
              </tr>
              <tr>
                <td valign="top" bgcolor="#CCCCCC" height="1"></td>
                <td bgcolor="#CCCCCC" height="1"></td>
              </tr>
              </table>
            <table width="100%" border="0" id="tc_table" class="lang_content_table">
              <tr>
                <td><table width="100%" border="0">
                  <tr class="content">
                    <td width="120">相簿標題:<br>
                    (建議最多12字)
                    </td>
                    <td><input name="cp_subject" type="text" id="cp_subject" size="50"   value="<? if ($action=='add'){ echo '';} else {echo $row['cp_subject'];}?>"></td>
                    </tr>
                  <tr class="content">
                    <td valign="top">簡介:<br>
                      (建議最多100字)</td>
                    <td><textarea name="cp_brief" cols="80" rows="4" id="cp_brief" class="content"><? if ($action=='add'){ echo '';} else {echo $row['cp_brief'];}?></textarea></td>
                    </tr>
                  </table></td>
              </tr>
            </table>
            
            
            <table width="100%" border="0" id="sc_table" class="lang_content_table">
              <tr>
                <td><table width="100%" border="0">
                  <tr class="content">
                    <td width="120">相簿标题：<br>(建议最多12字)</td>
                    
                    <td><input name="sp_subject" type="text" id="sp_subject" size="50" value="<? if ($action=='add'){ echo '';} else {echo $row['sp_subject'];}?>"></td>
                    </tr>
                  <tr class="content">
                    <td valign="top">简介:<br>
                      (建议最多100字)</td>
                    <td><textarea name="sp_brief" cols="80" rows="4" id="sp_brief"  class="content"><? if ($action=='add'){ echo '';} else {echo $row['sp_brief'];}?></textarea></td>
                    </tr>
                  </table></td>
              </tr>
            </table>
            
            
            <table width="100%" border="0" id="en_table" class="lang_content_table">
              <tr>
                <td><table width="100%" border="0">
                  <tr class="content">
                    <td width="120">Album Title:<br>(Suggesting Max. 30 words)</td>
                                        
                    <td><input name="ep_subject" type="text" id="ep_subject" size="50"value="<? if ($action=='add'){ echo '';} else {echo $row['ep_subject'];}?>"></td>
                    </tr>
                  <tr class="content">
                    <td valign="top">Brief:<br>
                      (Suggesting <br>
						Max. 100 words)</td>
                    <td><textarea name="ep_brief" cols="80" rows="4" id="ep_brief" class="content"><? if ($action=='add'){ echo '';} else {echo $row['ep_brief'];}?></textarea></td>
                    </tr>
                  </table></td>
              </tr>
            </table>
           
          <table width="100%" border="0" cellpadding="0" cellspacing="0" class="content">
            <tr>
              <td height="15"></td>
            </tr>
          </table>
           <?php if ($action =='edit'){?><input type="hidden" name="album_id" value="<?php echo $row['album_id'];?>"><?php }?>
           <input type="hidden" name="<? if ($action =='add'){ echo 'MM_insert';} else { echo 'MM_update';}?>" value="fHtmlEditor">
            <input type="button" name="Submit"  onClick="OnFormSubmit()" id="btn_submit">
          </form>
        </td>
      </tr>
      <tr>
        <td>&nbsp;</td>
      </tr>
    </table></td>
  </tr>
</table>
<?php include 'library/bottom.php'; ?>
</body>
</html>
