<?php
include 'connect/cms-config.php' ;
include 'requires/function.php' ;
include 'requires/session.php' ;

// include the class
include 'requires/class_resize.php' ;


// keep parameter in value
$page = escapeString($_GET['page']) ;
$page_mode = escapeString($_GET['page_mode']) ;
$order = escapeString($_GET['order']) ;
$type = escapeString($_GET['type']) ;
$search = escapeString($_GET['search']) ;

// get all branch
$branch_all     = [] ;
$get_branch = $mysqli->query("SELECT * FROM branch
                              WHERE deleted_at IS NULL") ;
if ( $get_branch->num_rows > 0 ){
    while ( $row_branch = $get_branch->fetch_assoc() ){
        $branch_all[$row_branch['branch_id']] = $row_branch['branch_name'] ;
    }
}

//trash media
if($_POST['trash_media']){
	$media_id = $_POST['trash_media'];
	$today_date = date("Y-m-d H:i:s");
	foreach($media_id as $value){
		$update = $mysqli->query("UPDATE media SET deleted_at = '$today_date' WHERE media_id = '$value' ");
	}
	if($update){
		$_SESSION['media_delete'] = 'success';
		header('Refresh:0');
		exit;
	}else{
		$_SESSION['media_delete'] = 'failed';
		header('Refresh:0');
		exit;
	}
}

// form submit
if ($_POST['hide'] == 1){
	
	$boolean_redirect = false ;

	// set image in variable
	$image = $_FILES["image"]["name"] ;

	
	// check status
	switch($_POST['hide_status']){
		case 'new' :

			if ( $image 	   != '' ){
				$filetype = $_FILES["image"]["type"];
				$filetype = explode('/', $filetype)[1];

				$mysqli->query("INSERT INTO media (filetype) VALUES ('$filetype')");
				 $id = $mysqli->insert_id;
				 $file_name 		= 'media-'.$id.'.'.$filetype ;

				if(move_uploaded_file( $_FILES["image"]["tmp_name"], $_SERVER['DOCUMENT_ROOT'].'/uploads/Media/'.$file_name )){
					$update = $mysqli->query("UPDATE media SET file = '$file_name' WHERE media_id = '$id'");
				} 
				if($update){
					$_SESSION['media_upload'] = 'success';
					header('Location: media-setting.php?page_mode=edit&page='.$id.'');
					exit;
				}else{
					$_SESSION['media_upload'] = 'failed';
					header('Refresh:0');
					exit;
				}

			}

		break ;
		case 'edit' :
			$media_id = $_POST['hidden_media_id'];
			$remove_photo 		= $_POST['remove_photo'] ;

			if ($remove_photo  == 1){
				$update = $mysqli->query("UPDATE media SET file = '', filetype = '' WHERE media_id = '$media_id'");
			}

			if($image != ''){
				
				$filetype = $_FILES["image"]["type"];
				$filetype = explode('/', $filetype)[1];

				$file_name 		= 'media-'.$media_id.'.'.$filetype ;

				if(move_uploaded_file( $_FILES["image"]["tmp_name"], $_SERVER['DOCUMENT_ROOT'].'/uploads/Media/'.$file_name )){
					$update = $mysqli->query("UPDATE media SET file = '$file_name' WHERE media_id = '$media_id'");
				} 
				if($update){
					$_SESSION['media_edit'] = 'success';
					header('Location: media-setting.php?page_mode=edit&page='.$media_id.'');
					exit;
				}else{
					$_SESSION['media_edit'] = 'failed';
					header('Location: media-setting.php?page_mode=edit&page='.$media_id.'');
					exit;
				}
			}
			
		break ;
		
	}
	
		
	
}

// mode type | all list | new | edit
switch($page_mode){
	
	// new customer
	case 'new' :

		// check permission
		if ( !permissionCheck($row_user, 'user-new-user-new') ){
			header('Location: index.php') ;
			exit ;
		}
		
		// active menu bar
		$active_main_menu = 'setting' ;
		$active_sub_menu = 'setting-media' ;
		
		
		// start header here
		include 'requires/page_header.php' ;
		include 'requires/page_top.php' ;
		
		?>
		<div class="warper container-fluid">   	
		<div class='container' style="background-color: white; border-radius: 10px;">
			<div class="page-header" style="margin: 30px 0px 0px 0px;padding: 0px;">
				<h1><?= $lang['Media']?> <small><?= $lang['new']?></small></h1></div>
			<div class="row">
				<div class="col-md-12">
                	<div class="error_message">
						<?php 
							if($_SESSION['media_upload'] == 'failed'){
								echo '<div class="result_error">Sorry. Some error occured. Uplaod failed!' .'<br /></div>' ;
							}
							unset($_SESSION['media_upload']);
						    unset($_SESSION['media_edit']);

						?>
                    </div>
					<div class="panel panel-default">
						<div class="panel-heading"></div>
                        <div class="panel-body">

                            <form method="post" class="form-horizontal" id="quotationForm" action="?page_mode=new" enctype="multipart/form-data" novalidate="novalidate">
                                <div class="form-group">
                                    <div class="col-sm-2 control-label"><?= $lang['Image']?></div>
                                    <div class="col-sm-9">
                                        <div class="file_upload">
                                            <div class="file_form">
                                                <input type="hidden" name="hide_image" value="" />
                                                <input type="hidden" name="remove_photo" value="">
                                                <input type="file" name="image" class="file_button control-label" tabindex="16" />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-sm-2 control-label"></div>
                                    <div class="col-sm-9">
                                        <input type="hidden" name="hide" value="1" />
                                        <input type="hidden" name="hide_status" value="new" />
                                        <button type="submit" class="btn" style="color:white;background-color: #5e5bd0;float:right; margin-top: 5px;width: 100px;"><?= $lang['submit']?></button>
                                        <input type="hidden" name="hide_user_id" value="" />
                                    </div>
                                </div>   
                            </form>
                        </div>
					</div>
				</div>
			</div>
		</div>
		</div>
		<?php
	break ;

	// edit media
	case 'edit' :

		$active_main_menu = 'setting' ;
		$active_sub_menu = 'setting-media' ;

		$mysqli_data = $mysqli->query("SELECT * FROM media WHERE media_id = '$page' LIMIT 1");
		$row_page = mysqli_fetch_assoc($mysqli_data);

		// start header here
		include 'requires/page_header.php';
		include 'requires/page_top.php';
		?>
		<div class="warper container-fluid">   	
		<div class='container' style="background-color: white; border-radius: 10px;">
			<div class="page-header" style="margin: 30px 0px 0px 0px;padding: 0px;">
				<h1><?= $lang['Media']?> <small><?= $lang['edit']?></small></h1></div>
			<div class="row">
				<div class="col-md-12">
                    <div class="error_message">
						<?php 
							
						if($_SESSION['media_edit'] == 'success'){
								echo '<div class="result_success">Media edit success' .'<br /></div>' ;
						}else if($_SESSION['media_edit'] == 'failed'){
								echo '<div class="result_error">Media edit failed' .'<br /></div>' ;
						}else if($_SESSION['media_upload'] == 'success'){
								echo '<div class="result_success">Media uplaoded sucess' .'<br /></div>' ;
						}
						unset($_SESSION['media_upload']);
						unset($_SESSION['media_edit']);
						?>
                    </div>
					<div class="panel panel-default">
						<div class="panel-heading"></div>
						<div class="panel-body">
							<form method="post" class="form-horizontal" id="quotationForm" action="?page_mode=edit&page=<?= $page ?>" enctype="multipart/form-data" novalidate="novalidate">
                                <div class="form-group">
                                    <div class="col-sm-2 control-label"><?= $lang['Image']?></div>
                                    <div class="col-sm-9">
                                        <div class="file_upload">
                                            <div class="file_form">
                                                <input type="hidden" name="hide_image" value="" />
                                                <input type="file" name="image" class="file_button control-label" tabindex="16" />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php if ($row_page['file'] != ''){ ?>
			                        <div class="form-group form-group-pdf">
			                            <div class="col-sm-2 control-label"><?= $lang['preview']?></div>
			                            <div class="col-sm-9">
			                            	<label class="remove_photo"><input type="checkbox" name="remove_photo" class="ui-checkbox tick" value="1">&nbsp;<?= $lang['Remove File']?></label>
			                            	<a href="<?= PATH.'uploads/Media/'.dataFilter($row_page['file']).'?v='.rand(100,1000).'' ?>" target="_blank">
			                            		<img src="<?= PATH.'uploads/Media/'.dataFilter($row_page['file']).'?v='.rand(100,1000).'' ?>" style="width:100px;" />
			                            	</a>
				                        </div>
			                        </div>
		                        <?php }else{ ?>
		                            <input type="hidden" name="remove_photo" value="" />
		                        <?php } ?>
								<div class="form-group">
									<div class="col-sm-2 control-label"></div>
									<div class="col-sm-9">
                                    	<input type="hidden" name="hide" value="1" />
                                        <input type="hidden" name="hide_status" value="edit" />
										<button type="submit" class="btn" style="color:white;background-color: #5e5bd0;float:right; margin-top: 5px;width: 100px;"><?= $lang['submit'] ?></button>
										<input type="hidden" name="hidden_media_id" value="<?= $row_page['media_id'] ?>" />
									</div>
								</div> 
								
							</form>
						</div>
					</div>
				</div>
			</div>
		</div>
		</div>
		<?php
	break ;
	// all customer list
	case 'all' :
	default :
		
		
	// active page
	$active_main_menu = 'setting' ;
	$active_sub_menu = 'setting-media' ;
	
	$limit = LIMIT;
		
	// pagination
	if (isset($page) && !empty($page)) { $product_page = $page ; } else { $product_page = 1 ; } // next and prev page (5 thing need to change)
	$start_from = ($product_page - 1) * $limit ; //end next and prev page
	
	// page query
	$mysqli_query = "SELECT * FROM media WHERE deleted_at is null";
	$mysqli_page = $mysqli->query($mysqli_query." ORDER BY created_at DESC LIMIT $start_from, " . $limit) ;
	
	// set search url
	$search_url = 'search='.$search ;
	
	// load pagination
	$page_pagination = nextPrevious($product_page, $limit, $search_url, $mysqli_query);
	

	// start header here
	include 'requires/page_header.php' ;
	include 'requires/page_top.php' ;
	
		?>
		<!-- Header Ends -->
<div class="warper container-fluid">   	
<div class='container' style="background-color: white; border-radius: 10px;">
	<div class="page-header" style="margin: 30px 0px 0px 0px;padding: 0px;">
		<div class="row">
		<div class="pull-left col">
			<h1><?= $lang['Media'] ?> <small><?= $lang['list'] ?></small></h1>
		</div>
	 	<div class="pull-right col">
			<a href="?page_mode=new" class="btn" style="color:white;background-color: #5e5bd0;">New Media</a>
		</div>
	</div>
	</div>


    <div class="result_success display_none" id="result_quantity_warning"><?= $lang['all_devices_for_the_selected_user_were_disconnected'] ?></div>
    <div class="result_success <?= ($_SESSION['media_delete']=='success' ? '' : 'display_none') ?>"><?= 'Success deleted' ?></div>
    <div class="result_error <?= ($_SESSION['media_delete']=='failed' ? '' : 'display_none') ?>"><?= 'Delete failed' ?></div>
		<?php 
        	unset($_SESSION['media_delete']);
        ?>


    <div class="panel panel-default">
		<div class="panel-heading"></div>
			<div class="panel-body">
				<div class="form-group">
					<div class="col-sm-2 control-label" style="text-align:right;"><?= $lang['Action'] ?></div>
					<div class="col-sm-9">
						<div class="file_upload">
                            <div class="file_form">
                                <select class="form-control"><option>Trash</option></select>
                            </div>
                        </div>
						<button type="button" id="trash_media_btn" class="btn" style="color:white;background-color: #5e5bd0;float:right; margin-top: 5px;width: 100px;"><?= $lang['submit'] ?></button>
					</div>
				</div> 
			</div>
		</div>

		<div class="panel panel-default">
			<div class="panel-heading"></div>
			<div class="panel-body">
				<form method="post" id="trash_media_form" novalidate>
					<table cellpadding="0" cellspacing="0" border="0" class="responsive table table-striped table-bordered" id="basic-datatable">
						<thead>
							<tr>
								<th><?= $lang['Action'] ?></th>
								<th><?= 'Media Url' ?></th>
								<th><?= 'Media Image' ?></th>
                                <th><?= $lang['created_date'] ?></th>
                                <th><?= $lang['trash'] ?></th>
							</tr>
						</thead>
						<tbody>
							<?php
							if ($mysqli_page->num_rows > 0){
								while ($row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC)){
									$media_id = $row_page['media_id'];
									$file = $row_page['file'];
									echo '
										<tr class="odd gradeX">
											<td class="align_center"><a href="?page_mode=edit&page='.$media_id.'"><i class="fa fa-edit"></i></a></td>
											<td class="align_center">'.PATH.'uploads/Media/'.dataFilter($row_page['file']).'</td>
											<td class="align_center"><img style="width:100px; height:100px" src="'.PATH.'uploads/Media/'.dataFilter($row_page['file']).'?v='.rand(100,1000).'" /></td>
											<td class="align_center">'.$row_page['created_at'].'</td>
											<td class="align_center"><input type="checkbox" name="trash_media[]" class="trash_media" value="'.$media_id.'" /></td>
										</tr>
									';
								}
							}else{
								echo '
								<tr class="odd gradeX">
									<td class="border_none" colspan="5">'.$lang['no_data'].'</td>	
								</tr>' ;
							}
							?>
							
						</tbody>
					</table>
				</form>
				<?= $page_pagination['page_pagination'] ?>
			</div>
		</div>
	</div>
</div>
        <?php
	break ;
}

// footer
include 'requires/page_footer.php' ;
?>
<script>
	$('select').select2();
	$('#trash_media_btn').click(function(){

		if(confirm('Are you sure to delete the selected item?')){
			$('#trash_media_form').submit();
		}
	});
</script>