<?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 	= 'ourinbox' ;
$active_menu 		= 'service-request-sub' ;


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

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

$mysqli_query_main = "SELECT a.main_id, b.title FROM setting_request a
					  LEFT JOIN setting_request_translation b ON ( a.main_id = b.main_id )
				      WHERE a.deleted_at IS NULL AND b.lang = 'en' " . $user_branch_permission_sql_symbol ;
$mysqli_main  	   = $mysqli->query( $mysqli_query_main ) ;

// mode type | all list | new | edit
switch($page_mode){

	case 'new' :
	case 'edit' :

		// check query exsits
		$submit_type = 'new' ;
		$mysqli_page = $mysqli->query("SELECT * FROM setting_request_sub
									   WHERE sub_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 ){

			if ( $page == '' ){
				$mysqli->query( "INSERT INTO setting_request_sub 
							    ( created_at ) VALUES 
							    ( '".TODAYDATE."' )" ) ;
				$page = $mysqli->insert_id ;	
			}

			// resize image
	        // set image in variable
			$image 		  = $_FILES["image"]["name"] ;
			$image_query  = '' ;
			$remove_photo = $_POST['remove_photo'] ;
			if ($remove_photo == 1){
				$image = '' ;	
				$image_query = "file = ''," ;
			}

			if ( $image != '' ){
				$get_image = pathinfo($image) ;

				$create_image = reCreateImage('Request', 'sub-'.$page, 'sub-'.$page, '', $image, $_FILES["image"]["type"], $_FILES['image']['tmp_name']) ;
				// Image uploads when exists
				if ($create_image['result'] && is_array($create_image['crop']) && count($create_image['result']) > 0){
					$resizeObj = new resize($create_image['original']) ; // Initialise load image
					foreach($create_image['crop'] as $value){
						// Resize image (options: exact, portrait, landscape, auto, crop)
						$resizeObj -> resizeImage($value['width'], $value['height'], $value['type']) ;
						$resizeObj -> saveImage($value['source'], 70) ; // Save image	
					}
					$get_image   = pathinfo($create_image['image']) ;
					$image_query = "file = '".$create_image['image']."'," ;
				}
			}

			$array_branch = [] ;
			foreach ( $_POST['branch'] as $k_branch => $v_branch ){
				$array_branch[] = escapeString( $v_branch ) ;
			}

			// update database
			$mysqli->query( "UPDATE setting_request_sub SET
							".$image_query."
							branch       = '/".implode('/', $array_branch)."/',
							main_id      = '".escapeString($_POST['main_id'])."',
							type 		 = '".escapeString($_POST['type'])."',
							title        = '".escapeString($_POST['title'])."'
							WHERE sub_id = '".$page."'" ) ;

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

				checkLangUpdate( 'setting_request_sub_translation', 'sub_id', $page, $klang, [ 
					'title' 	  => [ 'type' => 'input', 'value' => $title   ], 
					'description' => [ 'type' => 'input', 'value' => $description ]
				] ) ;
			}


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

		}

		// 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>Sub 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-request-sub.php?page_mode=edit&page=<?= $page ?>&type=edit" novalidate="novalidate">

                    	<div class="form-group show_branch_action">
                            <div class="col-sm-2 control-label"><?= $lang['branch']?></div>
                            <div class="col-sm-9">
                                <select name="branch[]" class="form-control ui-search-input chosen-select select2-basic-single" multiple required>
                                	<?php
                            		foreach ( $branch_all as $key => $value ) {
                            			echo '<option value="'.$key.'" '. ( strpos( $row_page['branch'], '/'.$key.'/' ) !== false ? 'selected' : '' ) .' >'.$value.'</option>';
                            		}
                                	?>
                                </select>
                            </div>
                        </div>
                    	<div class="form-group">
                            <div class="col-sm-2 control-label">Type</div>
                            <div class="col-sm-9">
                                <select name="type" class="chosen-select2 form-control tab_index ui-dropdown-select ui-search-input select2-basic-single">
                                	<option value="">Select Type</option>
                                	<option value="item" 		<?= ( $row_page['type'] == 'item' ? 'selected' : '' ) ?> >Item</option>
                                	<option value="item-size" 	<?= ( $row_page['type'] == 'item-size' ? 'selected' : '' ) ?> >Item with Size</option>
                                	<option value="association" <?= ( $row_page['type'] == 'association' ? 'selected' : '' ) ?> >Association</option>
                                	<option value="training"    <?= ( $row_page['type'] == 'training' ? 'selected' : '' ) ?> >Training</option>
                                	<option value="reservation" <?= ( $row_page['type'] == 'reservation' ? 'selected' : '' ) ?> >Reservation</option>
		                        </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-sm-2 control-label">Main Category</div>
                            <div class="col-sm-9">
                            	<select name="main_id" class="chosen-select select2-basic-single form-control">
                            		<?php
									if ( $mysqli_main->num_rows > 0 ){
										while ( $row_main = $mysqli_main->fetch_assoc() ){
											echo '<option '.( $row_main['main_id'] == $row_page['main_id'] ? 'selected' : '' ).' value="'.$row_main['main_id'].'">'.dataFilter($row_main['title']).'</option>' ;
										}
									}
                            		?>
                            	</select>
                            </div>
                        </div>

                    	<?php 
                		echo showTabs( 'setting_request_sub_translation', 'sub_id', $page, [ 
                			'title'       => [
                				'type'    => 'input', 
                				'title'   => $lang['title']
                			], 
                			'description' => [
                				'type'    => 'textarea', 
                				'title'   => 'Description'
                			]
                		]) ; 
                    	?>

                        <div class="form-group">
                            <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['file']) ?>" />
                                        <input type="hidden" name="remove_photo" value="">
                                        <input type="file" name="image" class="file_button control-label" <?= $input_block ?> />
                                    </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/Request/'.dataFilter($row_page['file']) ?>" target="_blank">
	                            		<img src="<?= PATH.'uploads/Request/'.dataFilter($row_page['file']) ?>" 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">
                                <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 announcement list
	case 'all' :
	default :
		
		// query type
		$search_name = escapeString($_GET['search_name']) ;
		$search_type = escapeString($_GET['search_type']) ;
		
		// search query
		if ( $search_name  != '' ){
			$search_query  .= " AND ( b.title LIKE '%".$search_name."%' )" ;
		}
		if ( $search_type 	!= '' ){
			$search_query  .= " AND ( a.type = '".$search_type."' )" ;
		}


		// form submit
		if ( $_POST['hide'] == '1' && $_POST['hide_status'] == 'action' ){
			switch($_POST['page_action']){
				case 'trash':
					$mysqli_query 	= "UPDATE setting_request_sub SET deleted_at = '".TODAYDATE."' WHERE sub_id = " ;
					$trash_page 	= trashPage('setting_request_sub', $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_name='.$search_name.'&search_type='.$search_type ;
		
		// page query
		$mysqli_query = "SELECT a.sub_id, a.main_id, a.type, b.title, ( SELECT balance FROM setting_request_movement WHERE deleted_at IS NULL AND main_id = '0' AND sub_id = a.sub_id ORDER BY movement_id DESC LIMIT 1 ) as balance FROM setting_request_sub a
						 LEFT JOIN setting_request_sub_translation b ON ( a.sub_id = b.sub_id )
						 WHERE a.deleted_at IS NULL AND b.lang = 'en' " . $search_query . $user_branch_permission_sql_symbol ;
		$mysqli_page = $mysqli->query( $mysqli_query." ORDER BY a.sub_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>Sub Category <small><?= $lang['list']?></small></h1>
				</div>
				<div class="pull-right col">
					<?php if ( permissionCheck($row_user, 'our-category-sub-new') ){ ?>
						<a href="app-request-sub.php?page_mode=new" class="btn" style="color:white;margin:5px;background-color: #5e5bd0;margin-top: 5px;" target="_blank"><?= $lang['add_new']?></a>
					<?php } ?>
				</div>
			</div>
			
		    <div class="panel panel-default" id="basic-table-title">
		        <div class="panel-heading">search</div>
		        <div class="panel-body">
		            <form method="get" class="form-horizontal">
		                <div class="form-group">
		                    <label class="col-sm-2 control-label"><?= $lang['Name'] ?></label>
		                    <div class="col-sm-9">
		                        <input type="text" name="search_name" value="<?= $search_name ?>" class="form-control" />
		                    </div>
		                </div>
	                    <div class="form-group">
		                    <label class="col-sm-2 control-label"><?= $lang['type'] ?></label>
		                    <div class="col-sm-9">
		                        <select class="form-control" name="search_type">
		                        	<option value="">Select Type</option>
                                	<option value="item" 		<?= ( $search_type == 'item' ? 'selected' : '' ) ?> >Item</option>
                                	<option value="association" <?= ( $search_type == 'association' ? 'selected' : '' ) ?> >Association</option>
                                	<option value="training"    <?= ( $search_type == 'training' ? 'selected' : '' ) ?> >Training</option>
                                	<option value="reservation" <?= ( $search_type == 'reservation' ? 'selected' : '' ) ?> >Reservation</option>
		                        </select>
		                    </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="float:right;color:white;width:100px;background-color: #5e5bd0;margin-top: 5px;"><?= $lang['submit'] ?></button>
		                    </div>
		                </div>
		            </form>
		        </div>
		    </div>

            <form method="post">
                
                <?php if ( permissionCheck($row_user, 'our-category-sub-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;width:100px;background-color: #5e5bd0;" value="<?= $lang['submit']?>" />
                    </div>
                </div>
                <?php } ?>

                <div class="panel panel-default">
                    <div class="panel-heading">listing</div>
                    <div class="panel-body">
						<table cellpadding="0" cellspacing="0" border="0" class="listing-table responsive table table-striped table-bordered" id="basic-datatable">
							<thead>
								<tr>
									<th><?= $lang['Action']?></th>
									<th><?= $lang['type']?></th>
									<th><?= $lang['title']?></th>
									<th>Balance</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['sub_id'] ;
		
										echo '
										 <tr class="odd gradeX">
										 	<td class="align_center">' ;
												if ( permissionCheck($row_user, 'our-category-sub-edit') ){
													echo '
										 			<a title="Edit Current Request" href="app-request-sub.php?page_mode=edit&page='.$id.'"><i class="fa fa-edit"></i></a>' ;
												}else{
													echo '-' ;
												}
												if ( permissionCheck($row_user, 'our-category-sub-stock') ){
													echo '
													<span class="split">|</span>
										 			<a title="Stock Movement" target="_blank" href="app-request-stock.php?page_mode=all&main_id=&sub_id='.$id.'"><i class="fa fa-eye"></i></a>' ;
												}else{
													echo '-' ;
												}
											echo '
										 	</td>
											<td class="text-center">'.ucwords($row_page['type']).'</td>
											<td class="text-center">'.dataFilter($row_page['title']).'</td>
											<td class="text-center">'.( $row_page['balance'] != '' ? $row_page['balance'] : '0' ).'</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>
		</div>
		<?php
	break ;
}

include 'requires/page_footer.php' ;
?>