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

// active menu bar
$active_main_menu   = 'service' ;
$active_sub_menu    = 'redeem' ;
$active_menu        = 'redeem-list-list' ;

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

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

		// check query exsits
		$submit_type = 'new' ;
		$mysqli_page = $mysqli->query("SELECT * FROM redeem_category
									   WHERE category_id = '".$category_id."' 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 ( $category_id == '' ){
				$mysqli->query( "INSERT INTO redeem_category 
							    ( created_at ) VALUES 
							    ( '".TODAYDATE."' )" ) ;
				$category_id = $mysqli->insert_id ;	
			}





			// delete all department & receiver
			$receiver_type		= dataFilter($_POST['receiver_type']) ;
			$receiver_to 		= $_POST['receiver_to'] ;
			$receiver_to_dept 	= $_POST['receiver_to_dept'] ;

			$selected_staff     = [] ;
			$selected_depart    = [] ;
			if ( $receiver_type == '0' ){

				$mysqli_staff = $mysqli->query("SELECT staff_id, staff_name, staff_idno FROM staff
												WHERE ( staff_date_resigned IS NULL || staff_date_resigned = '0000-00-00' || staff_date_resigned >= '".TODAYDATE."' ) AND deleted_at IS NULL ") ;
				if ( $mysqli_staff->num_rows > 0 ){
					while ( $row_staff = $mysqli_staff->fetch_assoc() ){
						if ( !in_array( $row_staff['staff_id'], $prev_staff_id ) || $is_update_send ) {
							// pushToUserCron( 'redeem_category', $category_id, $row_staff['staff_id'], 'Redeem', $notification_title ) ;
						}
					}
				}

			}elseif ( $receiver_type == '1' ){

				if( !empty( $receiver_to ) ){
					for ( $i = 0 ; $i < count($receiver_to) ; $i++ ){
						if ( $receiver_to[$i] != '' ){
							$reset_staff      = $receiver_to[$i] ;
							$selected_staff[$reset_staff] = $reset_staff ;

							if ( !in_array( $reset_staff, $prev_staff_id ) || $is_update_send ) {
								// pushToUserCron( 'redeem_category', $category_id, $reset_staff, 'Redeem', $notification_title ) ;
							}
						}
					}
				}

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

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

							// save into 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']] = $row_depart_staff['staff_id'] ;

										if ( !in_array( $row_depart_staff['staff_id'], $prev_staff_id ) || $is_update_send ) {
											// pushToUserCron( 'redeem_category', $category_id, $row_depart_staff['staff_id'], 'Redeem', $notification_title ) ;
										}
									}
								}
							}

						}
					}
				}
			}

			$selected_staff  = ( arrayCheck($selected_staff) ? '/'.implode( '/', $selected_staff ).'/' : '' ) ;
			$selected_depart = ( arrayCheck($selected_depart) ? '/'.implode( '/', $selected_depart ).'/' : '' ) ;




			// update database
			$mysqli->query( "UPDATE redeem_category SET
							staff_id        	  = '".$selected_staff."',
							department_id   	  = '".$selected_depart."',
							receiver_type 		  = '".escapeString($_POST['receiver_type'])."',
							category_mode   	  = '".escapeString($_POST['category_mode'])."',
							category_type   	  = '".escapeString($_POST['category_type'])."',
							number_of_times   	  = '".escapeString($_POST['number_of_times'])."',
							date_start   		  = '".escapeString($_POST['date_start'])."',
							date_end   			  = '".escapeString($_POST['date_end'])."',
							status   			  = '".escapeString($_POST['status'])."'
							WHERE category_id     = '".$category_id."'" ) ;

			foreach ( $LANGS as $klang => $vlang ){
				$title        = escapeString( $_POST['title_'.$klang] ) ;
				$content      = escapeString( $_POST['content_'.$klang] ) ;

				checkLangUpdate( 'redeem_category_translation', 'category_id', $category_id, $klang, [ 
					'title' 	=> [ 'type' => 'input', 'value' => $title   ], 
					'content' 	=> [ 'type' => 'input', 'value' => $content ]
				] ) ;
			}

			// refresh page
			header("Location:app-redeem-category.php?page_mode=edit&category_id=".$category_id."&success=1") ;
			$_SESSION['system_result'] = 'success-updated' ;
			exit ;
		}

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





		// get all requires 
		// get all staff
		$staff_list   = [] ;
		$mysqli_staff = $mysqli->query("SELECT staff_id, staff_name, staff_idno FROM staff
										WHERE ( staff_date_resigned IS NULL || staff_date_resigned = '0000-00-00' || staff_date_resigned >= '".TODAYDATE."' ) AND 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']) ;
			}
		}

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

		// 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']) : [] ) ;


		// start header here
		include 'requires/page_header.php';
		include 'requires/page_top.php';
		?>
		<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(){
			$("#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=receiver_type]').on('change', function(){
	            hideshowlist($(this).val()) ;
	        });

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

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

			function hideshowlist(id){
	        	if ( id == '0' ){
	                $('.stafflist').hide();
	                $('.stafflist').next(".select2-container").hide();
	                $('.departmentlist').hide();
	                $('.departmentlist').next(".select2-container").hide();
	            }else 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='container' style="background-color: white; border-radius: 10px;">
			<div class="page-header" style="margin: 30px 0px 0px 0px;padding: 0px;"><h1>Redeem Category <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 details 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="app-redeem-category.php?page_mode=edit&category_id=<?= $category_id ?>&type=edit" novalidate="novalidate">

                    	<div class="form-group">
                            <div class="col-sm-2 control-label">To</div>
                            <div class="col-sm-9">

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

				                <div class="div_radio_select">
				                	<div class="stafflist">
				                		<div class="stafflist_select">
											<select name="receiver_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="receiver_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>

                    	<?php 
                		echo showTabs( 'redeem_category_translation', 'category_id', $category_id, [ 
                			'title'   => [
                				'type'    => 'input', 
                				'title'   => $lang['title']
                			], 
                			'content' => [
                				'type'    => 'textarea', 
                				'title'   => $lang['Content']
                			]
                		]) ; 
                    	?>

                        <div class="form-group">
                            <div class="col-sm-2 control-label">Number of Times</div>
                            <div class="col-sm-9">
                                <input type="text" name="number_of_times" class="form-control ui-search-input" value="<?= dataFilter($row_page['number_of_times']) ?>" placeholder="Number of Times" />
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label">Category Mode</div>
                            <div class="col-sm-9">
                                <select name="category_mode" class="form-control ui-search-input">
                                	<option value="normal" <?= ( $row_page['category_mode'] == 'normal' ? 'selected' : '' ) ?> >Normal</option>
                                	<option value="custom" <?= ( $row_page['category_mode'] == 'custom' ? 'selected' : '' ) ?> >Custom</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label">Category Type</div>
                            <div class="col-sm-9">
                                <select name="category_type" class="form-control ui-search-input">
                                	<option value="all" <?= ( $row_page['category_type'] == 'all' ? 'selected' : '' ) ?> >All</option>
                                	<option value="date" <?= ( $row_page['category_type'] == 'date' ? 'selected' : '' ) ?> >Date</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label">Date Start</div>
                            <div class="col-sm-9">
                                <input type="date" name="date_start" class="form-control ui-search-input" value="<?= dataFilter($row_page['date_start']) ?>" placeholder="Date Start" />
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label">Date End</div>
                            <div class="col-sm-9">
                                <input type="date" name="date_end" class="form-control ui-search-input" value="<?= dataFilter($row_page['date_end']) ?>" placeholder="Date End" />
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label">Status</div>
                            <div class="col-sm-9">
                                <select name="status" id="status" class="form-control ui-search-input">
                                	<option value="active"  <?= ( $row_page['status'] == 'active' ? 'selected' : '' ) ?> >Active</option>
                                	<option value="inactive" <?= ( $row_page['status'] == 'inactive' ? 'selected' : '' ) ?> >Inactive</option>
								</select>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label"></div>
                            <div class="col-sm-9">
                                <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" value="1">
                                <input type="hidden" name="page_status" value="<?= $submit_type ?>">
                            </div>
                        </div>   
                    </form>
                </div>
            </div>
        </div>
		</div>

		<?php
		
	break ;


	
	// all Redeem list
	case 'all' :
	default :
		
		$search_title 		= escapeString($_GET['search_title']) ;
		$search_date 		= ( $_GET['search_date']!= '' ? date('Y-m-d', strtotime($_GET['search_date'])) : '' ) ;
		
		// query type
		$search_query 		= '' ;
		
		// search query
		if( $search_title  != ''){
			$search_query  .= " AND b.title LIKE '%".$search_title."%'" ;
		}
		if ( $search_date  != '' ){
		    $search_query  .= " AND a.created_at like '%".$search_date."%' " ;
		}
		
		// form submit
		if ( $_POST['hide'] == '1' && $_POST['hide_status'] == 'action' ){
			switch($_POST['page_action']){
				case 'trash':
					$mysqli_query 	= "UPDATE redeem_category SET deleted_at = '".TODAYDATE."' WHERE category_id = " ;
					$trash_page 	= trashPage('category', $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.'&search_title='.$search_title.'&search_date='.$search_date.'&page_mode='.$page_mode ;
		
		// page query
		$mysqli_query 	= "SELECT a.category_id, a.status, a.created_at, b.title FROM redeem_category a
						   LEFT JOIN redeem_category_translation b ON ( a.category_id = b.category_id )
						   WHERE a.deleted_at IS NULL AND b.lang = 'en' " . $search_query ;
		$mysqli_page 	= $mysqli->query( $mysqli_query." ORDER BY a.category_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='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>Redeem Category <small><?= $lang['list']?></small></h1>
						</div>
                	<div class="pull-right col">
				<?php if ( permissionCheck($row_user, 'redeem-category-new') ){ ?>
					<a href="app-redeem-category.php?page_mode=new" class="btn" style="color:white;background-color: #5e5bd0;" target="_blank"><?= $lang['add_new']?></a>
				<?php } ?>
					</div>
				</div>
			</div>
			
		    <div class="panel panel-default" id="basic-table-title">
		        <div class="panel-heading"></div>
		        <div class="panel-body">
		            <form method="get" class="form-horizontal">
		                <div class="form-group">
		                    <label class="col-sm-2 control-label"><?= $lang['Subject'] ?></label>
		                    <div class="col-sm-9">
		                        <input type="text" name="search_title" value="<?= $search_title ?>" class="form-control" />
		                    </div>
		                </div>
	                    <div class="form-group">
		                    <label class="col-sm-2 control-label"><?= $lang['date'] ?></label>
		                    <div class="col-sm-9">
		                        <input class="form-control" name="search_date" type="date" value="<?= $search_date ?>" placeholder="Date Resigned">
		                    </div>
		                </div>
		                <div class="form-group">
		                    <div class="col-sm-11">
		                        <input type="hidden" name="page_mode" value="<?= $page_mode ?>" />
		                        <input type="hidden" name="search" value="<?= $search ?>" />
		                        <button type="submit" class="btn" style="color:white;background-color: #5e5bd0;float:right; margin-top: 5px;width: 100px;"><?= $lang['submit'] ?></button>
		                    </div>
		                </div>
		            </form>
		        </div>
		    </div>

            <form method="post">
                
                <?php if ( permissionCheck($row_user, 'redeem-category-trash') ){ ?>
                <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" style="color:white; background-color:#5e5bd0; width:100px;" 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['status']?></th>
									<th>Created 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['category_id'] ;
		
										echo '
										 <tr class="odd gradeX">
										 	<td class="align_center">' ;
												if ( permissionCheck($row_user, 'redeem-category-edit') ){
													echo '
										 			<a title="Edit Current Redeem" href="app-redeem-category.php?page_mode=edit&category_id='.$id.'"><i class="fa fa-edit"></i></a>' ;
												}else{
													echo '-' ;
												}
											echo '
										 	</td>
											<td>'.dataFilter($row_page['title']).'</td>
											<td class="text-center">'.resetStatus($row_page['status']).'</td>
											<td class="text-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>
										<td class="border_none"></td>
									</tr>' ;
								}
								?>
							</tbody>
						</table>
						<?= $page_pagination['page_pagination'] ?>
                    </div>
                </div>
			</form>
		</div>
		</div>
		<?php
	break ;

}
// footer
include 'requires/page_footer.php' ;
?>