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

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

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

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

// active catalog bar
$active_main_menu 	= 'service' ;
$active_sub_menu 	= 'catalog' ;
$active_menu 		= 'catalog-sub-category' ;

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

		// check query exsits
		$submit_type = 'new' ;
		$mysqli_page = $mysqli->query("SELECT * FROM catalog_category
									   WHERE category_id = '".$page."' AND category_type = 'sub' 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 catalog_category ( category_type, created_at ) VALUES ( 'sub', '".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('CatalogCategory', $page, $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']."'," ;
				}
			}
			
			// update database
			$mysqli->query("UPDATE catalog_category SET
							".$image_query."
							category_parent = '".escapeString($_POST['category_parent'])."',
							title           = '".escapeString($_POST['title'])."',
							sortable        = '".escapeString($_POST['sortable'])."',
							updated_at      = '".TODAYDATE."'
							WHERE category_id = '".$page."'") ;
			
			// refresh page
			header("Location:app-catalog-subcategory.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>Catalog 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-catalog-subcategory.php?page_mode=edit&page=<?= $page ?>&type=edit" novalidate="novalidate">
                        <div class="form-group">
                            <div class="col-sm-2 control-label"><?= $lang['title'] ?></div>
                            <div class="col-sm-9">
                                <input type="text" name="title" class="form-control ui-search-input" value="<?= dataFilter($row_page['title']) ?>" placeholder="<?= $lang['title'] ?>" >
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-sm-2 control-label">Sortable</div>
                            <div class="col-sm-9">
                                <input type="text" name="sortable" class="form-control ui-search-input" value="<?= dataFilter($row_page['sortable']) ?>" placeholder="Sortable" >
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-sm-2 control-label">Main Category</div>
                            <div class="col-sm-9">
                                <select name="category_parent" class="chosen-select2 form-control tab_index ui-dropdown-select ui-search-input select2-basic-single">
                                	<option value="">Select Category</option>
		                            <?php
		                            $mysqli_category = $mysqli->query("SELECT * FROM catalog_category
		                                                               WHERE deleted_at IS NULL AND category_type = 'main' ORDER BY sortable") ;
		                            if ( $mysqli_category->num_rows > 0 ){
		                                while ( $row_category = $mysqli_category->fetch_assoc() ){
		                                    echo '<option '.( $row_category['category_id'] == $row_page['category_parent'] ? 'selected' : '' ).' value="'.$row_category['category_id'].'">'.dataFilter($row_category['title']).'</option>' ;

		                                }
		                            }
		                            ?>
		                        </select>
                            </div>
                        </div>

                        <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/CatalogCategory/'.dataFilter($row_page['file']) ?>" target="_blank">
	                            		<img src="<?= PATH.'uploads/CatalogCategory/'.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 list
	case 'all' :
	default :
		
		// query type
		$search_query = '' ;
		
		// search query
		if ($search != ''){
			$search_query .= " AND ( title LIKE '%".$search."%' )" ;
		}
		
		// form submit
		if ($_POST['hide'] == '1' && $_POST['hide_status'] == 'action'){
			// trash item
			switch($_POST['page_action']){
				case 'trash':
					$mysqli_query = "UPDATE catalog_category SET
									 deleted_at      = '".TODAYDATE."'
									 WHERE category_id = " ;
					$trash_page = trashPage('catalog_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 ;
		
		// page query
		$mysqli_query = "SELECT * FROM catalog_category
						 WHERE deleted_at IS NULL AND category_type = 'sub' " . $search_query ;
		$mysqli_page = $mysqli->query($mysqli_query." ORDER BY category_id 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>Catalog Sub Category <small><?= $lang['list'] ?></small></h1>
					</div>
                	<div class="pull-right col">
						<a href="app-catalog-subcategory.php?page_mode=new" class="btn" style="color:white;background-color: #5e5bd0;" target="_blank"><?= $lang['add_new'] ?></a>
					</div>
				</div>
			</div>

            <form method="post">
                <!-- 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>
                <!-- end trash -->
                <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['title'] ?></th>
									<th><?= $lang['date'] ?></th>
									<th>Sortable</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'] ;
										$title = dataFilter($row_page['title']) ;
		
										echo '
										 <tr class="odd gradeX">
										 	<td class="align_center">
										 		<a title="'.$lang['Edit'].'" href="app-catalog-subcategory.php?page_mode=edit&page='.$id.'"><i class="fa fa-edit"></i></a>
										 	</td>
											<td><a href="app-catalog-subcategory.php?page_mode=edit&page='.$id.'">'.$title.'</a></td>
											<td>'.resetDateFormat($row_page['created_at']).'</td>
											<td>'.dataFilter($row_page['sortable']).'</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 ;
}
// footer
include 'requires/page_footer.php' ;
?>