<?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']) ;
$type 				= escapeString($_GET['type']) ;
$search 			= escapeString($_GET['search']) ;

// active menu bar
$active_main_menu 	= 'service' ;
$active_sub_menu 	= 'documentation' ;
$active_menu 		= 'documentation' ;

// check permission
if ( !permissionCheck($row_user, 'documentation') ){
	header('Location: index.php') ;
	exit ;
}

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

		// check query exsits
		$submit_type = 'new' ;
		$mysqli_page = $mysqli->query("SELECT * FROM documentation
									   WHERE documentation_id = '".$page."' LIMIT 1");
		if ($mysqli_page->num_rows > 0){
			// keep query value in array
			$row_page    = $mysqli_page->fetch_array(MYSQLI_ASSOC) ;
			$submit_type = 'edit' ;
		}

		// update database
		if ( isset($type) && ( $type == 'new' || $type == 'edit' ) && $_POST['hide'] == 1 ){

			// keep value in variable
			$page_title      = escapeString($_POST['title']) ;
			$page_title      = ($page_title != '' ? $page_title : 'No Title') ;

			if ( $page == '' ){
				$mysqli->query( "INSERT INTO documentation 
							    (author_id, created_at) VALUES 
							    ('".$_SESSION['system_id']."', '".TODAYDATE."')" ) ;
				$page = $mysqli->insert_id ;	
			}

			// resize image
			$image = $_FILES["image"]["name"] ;

			// remove photo
			$remove_photo = $_POST['remove_photo'] ;
			if ( $remove_photo == 1 ){
				$image 		 = '' ;	
				$image_query = "documentation_file_type = '',
								documentation_file = ''," ;
			}

			$type 					= dataFilter($_POST['documentation_receiver_type']) ;
			$documentation_to 		= $_POST['documentation_to'] ;
			$documentation_to_dept 	= $_POST['documentation_to_dept'] ;

			// delete all documentation department & receiver
			$selected_staff  = [] ;
			$selected_depart = [] ;
			if ( $type == '1' ){
				if( !empty( $documentation_to ) ){
					for ( $i = 0 ; $i < count($documentation_to) ; $i++ ){
						if ( $documentation_to[$i] != '' ){
							$reset_staff      = $documentation_to[$i] ;
							$selected_staff[] = $reset_staff ;
							pushToUserCron( 'documentation', $page, $reset_staff, 'Documentation', 'Documentation has been update.' ) ;
						}
					}
				}

			}else{
				if( !empty( $documentation_to_dept ) ){
					$array_depart = [] ;
					for ( $i = 0 ; $i < count($documentation_to_dept) ; $i++ ){

						$department_id = $documentation_to_dept[$i] ;
						if ( $department_id != '' ){

							// save into documentation department 
							$selected_depart[]= $department_id ;

							// check department staff
							$reset_depart     = str_replace( ['(', ')'], '', $department_id ) ;
							$get_depart_staff = $mysqli->query( "SELECT staff_id FROM staff_department
																 WHERE deleted_at IS NULL AND department_id = '".$reset_depart."'") ;
							if ( $get_depart_staff->num_rows > 0 ){
								while ( $row_depart_staff = $get_depart_staff->fetch_assoc() ){
									if ( !in_array($row_depart_staff['staff_id'], $array_depart) ){
										$array_depart[] = $row_depart_staff['staff_id'] ;
										$selected_staff = $row_depart_staff['staff_id'] ;
										pushToUserCron( 'documentation', $page, $row_depart_staff['staff_id'], 'Documentation', 'Documentation has been update.' ) ;
									}
								}
							}

						}
					}
				}
			}

			$selected_staff  = implode( '/', $selected_staff ) ;
			$selected_depart = implode( '/', $selected_depart ) ;
			
			// update database
			$mysqli->query( "UPDATE documentation SET
							".$image_query."
							staff_id 					= '".$selected_staff."',
							department_id 				= '".$selected_depart."',
							documentation_subject 		= '".$page_title."',
							documentation_format 		= '".escapeString($_POST['documentation_format'])."',
							documentation_message 		= '".escapeString($_POST['documentation_message'])."',
							documentation_video 		= '".escapeString($_POST['documentation_video'])."',
							documentation_receiver_type = '".escapeString($_POST['documentation_receiver_type'])."',
							updated_at            		= '".TODAYDATE."'
							WHERE documentation_id 		= '".$page."'") ;

			
			$get_image = pathinfo($image) ;
			if ( $get_image['extension'] == 'pdf' ){

				$file_name = $page.'-'.time().'.pdf' ;
				copy($_FILES["image"]["tmp_name"], 'uploads/Documentation/'.$file_name) ;

				// update database
				$mysqli->query("UPDATE documentation SET
								documentation_file_type = 'pdf',
								documentation_file      = '".$file_name."'
								WHERE documentation_id  = '".$page."'") ;
			}
		
			// add system log
			$array_remark = array('old' => array('title' => $row_page['documentation_subject']),
					  			  'new' => array('title' => $page_title)) ;
			// refresh page
			header("Location:documentation.php?page_mode=edit&page=".$page."&success=1") ;
			$_SESSION['system_result'] = 'success-updated' ;
			exit ;
		}

		if ( ( $page_mode == 'new' && !permissionCheck($row_user, 'documentation-new') ) ||
			 ( $page_mode == 'edit' && !permissionCheck($row_user, 'documentation-update') ) ){
			header('Location: documentation.php') ;
			exit ;
		}

		// start header here
		include 'requires/page_header.php';
		include 'requires/page_top.php';

		// get all requires 
		// get all staff
		$staff_list   = [] ;
		$mysqli_staff = $mysqli->query("SELECT staff_id, staff_name, staff_idno FROM staff
										WHERE deleted_at IS NULL ") ;
		if ( $mysqli_staff->num_rows > 0 ){
			while ( $row_staff = $mysqli_staff->fetch_assoc() ){
				$staff_list[$row_staff['staff_id']] = dataFilter($row_staff['staff_name']) . ' ( ' . dataFilter($row_staff['staff_idno']) . ' )' ;
			}
		}

		// get all requires 
		$department_list   = [] ;
		$mysqli_department = $mysqli->query("SELECT a.department_id, b.department_desc FROM setting_department a
						   				     LEFT JOIN setting_department_translation b ON ( a.department_id = b.department_id )
											 WHERE a.deleted_at IS NULL AND b.lang = 'en'") ;
		if ( $mysqli_department->num_rows > 0 ){
			while ( $row_department = $mysqli_department->fetch_assoc() ){
				$department_list[$row_department['department_id']] = dataFilter($row_department['department_desc']) ;
			}
		}

		// get all selected staff & department
		$receiver_staff  = ( $row_page['staff_id'] != '' ? explode('/', $row_page['staff_id']) : [] ) ;
		$receiver_depart = ( $row_page['department_id'] != '' ? explode('/', $row_page['department_id']) : [] ) ;

		?>

		<style>
		.stafflist_check, .departmentlist_check{
			margin-top:5px;
			margin-bottom:5px;
		}
		.form-group-pdf, .form-group-message, .form-group-video{
			display:none;
		}
		</style>

		<script>
		$(document).ready(function(){

			$(".documentation_format").change(function(){
				var thisKey = $(this) ;
				if ( thisKey.val() == 'pdf' ){
					$(".form-group-pdf").show() ;
					$(".form-group-message").hide() ;
					$(".form-group-video").hide() ;
				}else if ( thisKey.val() == 'video' ){
					$(".form-group-pdf").hide() ;
					$(".form-group-message").hide() ;
					$(".form-group-video").show() ;
				}else{
					$(".form-group-pdf").hide() ;
					$(".form-group-message").show() ;
					$(".form-group-video").hide() ;
				}
			}) ; 

			$("#checkAll").click(function(){
				$("#selectuser option").prop("selected","selected");
				$("#selectuser").trigger("change");
			});

			$("#unCheckAll").click(function(){
				$("#selectuser option").removeAttr("selected");
				$("#selectuser").trigger("change");
			});

			$("#checkAllDept").click(function(){
				$("#selectdept option").prop("selected","selected");
				$("#selectdept").trigger("change");
			});

			$("#unCheckAllDept").click(function(){
				$("#selectdept option").removeAttr("selected");
				$("#selectdept").trigger("change");
			});

			$('input[type=radio][name=documentation_receiver_type]').on('change', function(){
	            hideshowlist($(this).val()) ;
	        });

	        <?php if ( $submit_type == 'edit' ){ ?>
				hideshowlist('<?= $row_page['documentation_receiver_type'] ?>') ;
			<?php }else{ ?>
				hideshowlist(1) ;
			<?php } ?>

			$('input[type=radio][name=documentation_receiver_type]').on('change', function(){
	            hideshowlist($(this).val()) ;
	        });

	        function hideshowlist(id){
	        	if( id == '1' ){
	                $('.stafflist').show();
	                $('.departmentlist').hide();
	            }else{
	                $('.stafflist').hide();
	                $('.departmentlist').show();
	            }
	        }

			function hideshowlist(id){
	        	if ( id == '1' ){
	                $('.stafflist').show();
	                $('.stafflist').next(".select2-container").show();
	                $('.departmentlist').hide();
	                $('.departmentlist').next(".select2-container").hide();
	            }else{
	                $('.stafflist').hide();
	                $('.stafflist').next(".select2-container").hide();
	                $('.departmentlist').show();
	                $('.departmentlist').next(".select2-container").show();
	            }
	        }

		}) ;
		</script>

		<div class="warper container-fluid">   	
			<div class="page-header"><h1><?= $lang['documentation']?> <small><?= $lang[$page_mode] ?></small></h1></div>
			<?php
            if ($_SESSION['system_result'] != ''){
                switch($_SESSION['system_result']){
                    case 'success-updated' :
                        echo '
                        <div class="result_success">
                            '.$lang['Thank you your documentation has been updated'].'
                        </div>' ;	
                    break ;
                }
                unset($_SESSION['system_result']) ;
            }
            ?>
            <div class="panel panel-default">
                <div class="panel-heading"></div>
                <div class="panel-body">
                    <form method="post" class="form-horizontal" id="quotationForm" enctype="multipart/form-data" action="documentation.php?page_mode=edit&page=<?= $page ?>&type=edit" novalidate="novalidate">
                        <div class="form-group">
                            <div class="col-sm-2 control-label"><?= $lang['To1']?></div>
                            <div class="col-sm-9">

								<div class="div_radio">
				                	<label><input type="radio" name="documentation_receiver_type" id="type1" value="1" <?= ( $row_page['documentation_receiver_type'] == '1' ? 'checked' : '' ) ?> required /> <?= $lang['Individual']?></label>&nbsp;&nbsp;&nbsp;
				                	<label><input type="radio" name="documentation_receiver_type" value="2" <?= ( $row_page['documentation_receiver_type'] == '2' ? 'checked' : '' ) ?> required /> </i> <?= $lang['Department']?></label>
				                </div>

				                <div class="div_radio_select">
				                	<div class="stafflist">
				                		<div class="stafflist_select">
											<select name="documentation_to[]" id="selectuser" class="chosen-select form-control tab_index ui-dropdown-select ui-search-input select2-basic-single" multiple>
												<?php
												if ( count($staff_list) > 0 ){
													foreach ( $staff_list as $k => $v ){
														echo '<option value="'.$k.'" '.( in_array( $k, $receiver_staff ) ? 'selected' : '').'>'.$v.'</option>' ;
													}
												}
												?>
											</select>
										</div>
										<div class="stafflist_check">
											<a class="btn btn-xs btn-danger" id="checkAll"><i class="fa fa-check-circle"></i> </i> <?= $lang['Check All']?></a>
											<a class="btn btn-xs btn-danger" id="unCheckAll"><i class="fa fa-times-circle"></i> </i> <?= $lang['Uncheck All']?></a>
										</div>
									</div>
									<div class="departmentlist">
										<div class="departmentlist_select">
											<select name="documentation_to_dept[]" id="selectdept" class="chosen-select form-control tab_index ui-dropdown-select ui-search-input select2-basic-single" multiple>
												<?php
												if ( count($department_list) > 0 ){
													foreach ( $department_list as $k => $v ){
														echo '<option value="'.$k.'" '.( in_array( $k, $receiver_depart ) ? 'selected' : '').'>'.$v.'</option>' ;
													}
												}
												?>
											</select>
										</div>
										<div class="stafflist_check">
											<a class="btn btn-xs btn-danger" id="checkAllDept"><i class="fa fa-check-circle"></i> <?= $lang['Check All']?></a>
											<a class="btn btn-xs btn-danger" id="unCheckAllDept"><i class="fa fa-times-circle"></i> <?= $lang['Uncheck All']?></a>
										</div>
									</div>
				                </div>

                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label"><?= $lang['Subject']?></div>
                            <div class="col-sm-9">
                                <input type="text" name="title" class="form-control ui-search-input" value="<?= dataFilter($row_page['documentation_subject']) ?>" placeholder="<?= $lang['Subject']?>" >
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label"><?= $lang['Format']?></div>
                            <div class="col-sm-9">
                                <label><input type="radio" name="documentation_format" class="documentation_format" <?= ( $row_page['documentation_format'] == '' || $row_page['documentation_format'] == 'pdf' ? 'checked' : '' ) ?> value="pdf" /> PDF</label>
								<label><input type="radio" name="documentation_format" class="documentation_format" <?= ( $row_page['documentation_format'] == 'message' ? 'checked' : '' ) ?> value="message" /> <?= $lang['Message']?></label>
								<label><input type="radio" name="documentation_format" class="documentation_format" <?= ( $row_page['documentation_format'] == 'video' ? 'checked' : '' ) ?> value="video" /> <?= $lang['Video']?></label>
                            </div>
                        </div>
                        <div class="form-group form-group-pdf" <?= ( $row_page['documentation_format'] == '' || $row_page['documentation_format'] == 'pdf' ? 'style="display:block;"' : '' ) ?> >
                            <div class="col-sm-2 control-label"><?= $lang['photo']?></div>
                            <div class="col-sm-9">
                                <div class="file_upload">
                                    <div class="file_form">
                                        <input type="hidden" name="hide_image" value="<?= dataFilter($row_page['documentation_file']) ?>" />
                                        <input type="hidden" name="remove_photo" value="">
                                        <input type="file" name="image" class="file_button control-label" />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="form-group form-group-pdf" <?= ( $row_page['documentation_format'] == '' || $row_page['documentation_format'] == 'pdf' ? 'style="display:block;"' : '' ) ?> >
                            <div class="col-sm-2 control-label"><?= $lang['preview']?></div>
                            <div class="col-sm-9">
                                <?php
                                if ($row_page['documentation_file'] != ''){
                                    echo '
                                    <label class="remove_photo"><input type="checkbox" name="remove_photo" class="ui-checkbox tick" value="1">&nbsp;'.$lang['Remove'].' pdf</label>
                                    <a href="'.PATH.'uploads/Documentation/'.dataFilter($row_page['documentation_file']).'" target="_blank">'.$lang['Download'].'</a>' ;
                                }else{
                                    echo '
                                    <input type="hidden" name="remove_photo" value="">' ;	
                                }
                                ?>
                            </div>
                        </div>
                        <div class="form-group form-group-message" <?= ( $row_page['documentation_format'] == 'message' ? 'style="display:block;"' : '' ) ?> >
                            <div class="col-sm-2 control-label"><?= $lang['Message']?></div>
                            <div class="col-sm-9">
                            	<textarea name="documentation_message" class="documentation_message" id="editor1" rows="10" cols="80"><?= dataFilter($row_page['documentation_message']) ?></textarea>
		                        <script>
		                        // Replace the <textarea id="editor1"> with a CKEditor
		                        // instance, using default configuration.
		                        CKEDITOR.replace('editor1') ;
		                        </script>
                            </div>
                        </div>
                        <div class="form-group form-group-video" <?= ( $row_page['documentation_format'] == 'video' ? 'style="display:block;"' : '' ) ?> >
                            <div class="col-sm-2 control-label"><?= $lang['Video']?></div>
                            <div class="col-sm-9">
                            	<textarea name="documentation_video" class="documentation_video form-control ui-search-input"><?= dataFilter($row_page['documentation_video']) ?></textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label"></div>
                            <div class="col-sm-9">
                                <button type="submit" class="btn btn-purple" style="float:right"><?= $lang['submit']?></button>
                                <input type="hidden" name="hide" value="1">
                                <input type="hidden" name="page_status" value="<?= $submit_type ?>">
                            </div>
                        </div>   
                    </form>
                </div>
            </div>
		</div>

		<?php
		
	break ;
	
	// all documentation list
	case 'all' :
	default :
		
		// query type
		$search_query = '' ;
		
		// search query
		if ($search != ''){
			$search_query .= " AND (documentation_subject LIKE '%".$search."%')" ;
		}
		
		// form submit
		if ($_POST['hide'] == '1' && $_POST['hide_status'] == 'action'){
			// trash item
			switch($_POST['page_action']){
				case 'trash':
					$mysqli_query = "UPDATE " . documentation . " SET
									 deleted_at = '".TODAYDATE."'
									 WHERE documentation_id = " ;
					$trash_page = trashPage('documentation', $mysqli, $mysqli_query, $_POST['multiple_trash']) ;
				break;
			}
		}
		
		// 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
		
		// set search url
		$search_url = 'search='.$search ;
		
		// page query
		$mysqli_query = "SELECT * FROM documentation a
						 LEFT JOIN system_user b ON ( a.author_id = b.user_id )
						 WHERE a.deleted_at IS NULL " . $search_query ;
		$mysqli_page = $mysqli->query($mysqli_query." ORDER BY a.documentation_id DESC LIMIT $start_from, " . LIMIT) ;

		// 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="page-header">
				<h1><?= $lang['documentation']?> <small><?= $lang['list']?></small></h1>
				<?php if ( permissionCheck($row_user, 'documentation-new') ){ ?>
					<a href="documentation.php?page_mode=new" class="btn btn-purple" target="_blank"><?= $lang['add_new']?></a>
				<?php } ?>
			</div>

            <form method="post">
                
                <?php if ( permissionCheck($row_user, 'documentation-update') ){ ?>
                <div class="panel panel-default">
                    <div class="panel-body">
                        <select name="page_action" class="form-control selectpicker">
                            <option value=""><?= $lang['select']?></option>
                            <option value="trash"><?= $lang['move_to_trash']?></option>
                        </select>
                        <input type="hidden" name="hide" value="1" />
                        <input type="hidden" name="hide_status" value="action" />
                        <input type="submit" class="btn btn-purple" value="<?= $lang['submit']?>" />
                    </div>
                </div>
                <?php } ?>

                <div class="panel panel-default">
                    <div class="panel-heading"></div>
                    <div class="panel-body">
						<table cellpadding="0" cellspacing="0" border="0" class="responsive table table-striped table-bordered" id="basic-datatable">
							<thead>
								<tr>
									<th><?= $lang['Action']?></th>
									<th><?= $lang['Subject']?></th>
									<th><?= $lang['Author']?></th>
									<th><?= $lang['date']?></th>
                                    <th width="50"><?= $lang['trash']?></th>
								</tr>
							</thead>
							<tbody>
								<?php
								if ($mysqli_page->num_rows > 0){
									while ($row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC)){

										// default variable
										$id = $row_page['documentation_id'] ;
		
										echo '
										 <tr class="odd gradeX">
										 	<td class="align_center">' ;
												if ( permissionCheck($row_user, 'documentation-update') ){
													echo '
										 			<a title="'.$lang['Edit Current'].$lang['documentation'].'" href="documentation.php?page_mode=edit&page='.$id.'"><i class="fa fa-edit"></i></a>' ;
												}else{
													echo '-' ;
												}
											echo '
										 	</td>
											<td>'.dataFilter($row_page['documentation_subject']).'</td>
											<td class="align_center">'.dataFilter($row_page['user_name']).'</td>
											<td class="align_center">'.resetDateFormat($row_page['created_at']).'</td>
											<td>
												<div class="checkbox multiple_trash">
													<input type="checkbox" name="multiple_trash['.$id.']" class="trash_button" value="1">
													<label for="checkbox1"></label>
												</div>
											</td>
										</tr>';
									}
								}else{
									echo '
									<tr class="odd gradeX">
										<td class="border_none">'.$lang['no_data'].'</td>
										<td class="border_none"></td>
										<td class="border_none"></td>
										<td class="border_none"></td>
										<td class="border_none"></td>
									</tr>' ;
								}
								?>
							</tbody>
						</table>
						<?= $page_pagination['page_pagination'] ?>
                    </div>
                </div>
			</form>
		</div>
		<?php
	break ;
}
// footer
include 'requires/page_footer.php' ;
?>