<?php
if(isset($_GET['sil_id'])){
    $delete = $db->exec("DELETE FROM kategori WHERE id = '{$_GET['sil_id']}' LIMIT 1");
    echo b();
}

if($_POST AND !isset($_POST['siralama'])){

	if(!isset($_POST['ust_menu'])){ $_POST['ust_menu'] = 0; }
	if(!isset($_POST['alt_menu'])){ $_POST['alt_menu'] = 0; }
	
    if(isset($_GET['duzenle_id'])){
        $islem = $db->prepare("UPDATE kategori SET baslik = ?, description = ?, aciklama = ?, ust_menu = ?, alt_menu = ?, ust_kategori = ? WHERE id = ?");
        $islem = $islem->execute(array($_POST['baslik'],$_POST['description'],$_POST['aciklama'],$_POST['ust_menu'],$_POST['alt_menu'],$_POST['ust_kategori'],$_GET['duzenle_id']));
        $id = $_GET['duzenle_id'];
    }else{
        $islem = $db->prepare("INSERT INTO kategori SET baslik = ?, sef = ?, description = ?, aciklama = ?, ust_menu = ?, alt_menu = ?, ust_kategori = ?, sira = ?");
        $islem = $islem->execute(array($_POST['baslik'],'',$_POST['description'],$_POST['aciklama'],$_POST['ust_menu'],$_POST['alt_menu'],$_POST['ust_kategori'],999));
    	$id = $db->lastInsertId();
    }
    if($islem){
    	$sef = sef($_POST['baslik']).'-'.$id;
    	$islem = $db->prepare("UPDATE kategori SET sef = ? WHERE id = ?");
        $islem = $islem->execute(array($sef,$id));
        echo b();
    }else{
        echo h();
    }
}

if(isset($_GET['duzenle_id'])){
    $duzenle = $db->query("SELECT * FROM kategori WHERE id = '{$_GET['duzenle_id']}' LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    ?>
	<script type="text/javascript">
		$(function(){
			$('select[name="ust_kategori"] option[value="<?php echo $duzenle['ust_kategori']; ?>"]').attr('selected','select');
			$('[name="ust_menu"][value="<?php echo $duzenle['ust_menu']; ?>"]').attr('checked','checked');
			$('[name="alt_menu"][value="<?php echo $duzenle['alt_menu']; ?>"]').attr('checked','checked');
		});
	</script>
	<?php
}


if($_POST AND isset($_POST['siralama'])){

	$siralama = str_replace('\"', '"', $_POST['siralama']);
	$data = json_decode($siralama);
	$readbleArray = parseJsonArray($data);
	$i = 1;
	foreach($readbleArray as $row){
		$islem = $db->prepare("UPDATE kategori SET sira = ?, ust_kategori = ? WHERE id = ?");
		$islem = $islem->execute(array($i,$row['parentID'],$row['id']));
		$i++;
	}
	echo b();

}
?>
<div class="page-header">
	<div class="page-leftheader">
		<h4 class="page-title">Kategori Yönetimi</h4>
	</div>
	<div class="page-rightheader ml-auto d-lg-flex d-none">
		<ol class="breadcrumb">
			<li class="breadcrumb-item"><a href="index.php">Anasayfa</a></li>
			<li class="breadcrumb-item active" aria-current="page">Kategori Yönetimi</li>
		</ol>
	</div>
</div>
						
<div class="row">
	<div class="col-md-6">
		<div class="card">
			<div class="card-body">
				<div class="row">
					<div class="col-md-12">
							
						<?php 
							$cek = $db->query("SELECT * FROM kategori WHERE ust_kategori = 0 ORDER BY sira ASC", PDO::FETCH_ASSOC);
							if($cek->rowCount()){
						?>
						<form action="" method="post">
							<div class="dd" id="nestable" style="float: left;width: 100%">
					            <ol class="dd-list">
					                
					                <?php
							            function alt_eleman($x,$sayfa){
						            	  global $db;
							              $out = '';
							              $cek = $db->query("SELECT id, baslik FROM kategori WHERE ust_kategori = '{$x}' ORDER BY sira ASC ", PDO::FETCH_ASSOC);
										  if($cek->rowCount()){

							                $out.='<ol style="" class="dd-list">';
							                foreach ($cek as $v) {
							                  $out.='<li data-id="'.$v['id'].'" class="dd-item">
							                          <div class="dd-handle">
							                          #'.$v['id'].' - '.$v['baslik'].'
							                          </div>
							                          	<a href="'.$sayfa.'/sil/'.$v['id'].'" class="sil" style="float:right;color:red">Sil</span>
		                    							<a href="'.$sayfa.'/duzenle/'.$v['id'].'" class="duzenle" style="float:right;color:green;margin-right:20px">Düzenle</a>
							                         '.alt_eleman($v['id'],$sayfa);
							                }
							                $out.='</ol>';
							              }
							              return $out;
							            }

								        foreach ($cek as $ak) {
							              echo '<li data-id="'.$ak['id'].'" class="dd-item">
							                      <div class="dd-handle">
							                      	#'.$ak['id'].' - '.$ak['baslik'].'
							                      </div>
							                      	<a href="'.$sayfa.'/sil/'.$ak['id'].'" class="sil" style="float:right;color:red">Sil</span>
		                    						<a href="'.$sayfa.'/duzenle/'.$ak['id'].'" class="duzenle" style="float:right;color:green;margin-right:20px">Düzenle</a>
							                      '.alt_eleman($ak['id'],$sayfa).'
							                    </li>';
							            }
							        ?>

					                

					            </ol>
					        </div>
					        <input type="hidden" name="siralama" id="nestable-output">

							<div class="form-group row">
								<div class="col-md-12"><center><button type="submit" class="btn btn-info">Kaydet</button></center></div>
							</div>
				        </form>
				    	<?php } ?>

					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="col-md-6">
		<div class="card">
			<div class="card-body">
				<div class="row">
					<div class="col-md-12">
						
						<form class="form-horizontal" method="post" action="">

							<div class="form-group row">
							  <label class="col-sm-3 form-label">Üst Kategori</label>
							  <div class="col-sm-9">
								<select class="form-control" name="ust_kategori" required="">
									<option value="0">Anakategori</option>
									<?php
										$cek = $db->query("SELECT * FROM kategori", PDO::FETCH_ASSOC);
										if($cek->rowCount()){
											foreach( $cek as $c ){
												echo '<option value="'.$c['id'].'">#'.$c['id'].' - '.$c['baslik'].'</option>';
											}
										}
									?>
								</select>
							  </div>
							</div>

							<div class="form-group row">
								<label class="col-md-3 form-label">Başlık</label>
								<div class="col-md-9">
									<input type="text" class="form-control" name="baslik" value="<?php echo @$duzenle['baslik']; ?>" required="">
								</div>
							</div>
							<div class="form-group row">
								<label class="col-md-3 form-label">Kısa Açıklama (description)</label>
								<div class="col-md-9">
									<textarea class="form-control" rows="3" name="description"><?php echo @$duzenle['description']; ?></textarea>
								</div>
							</div>

							<div class="form-group row">
								<div class="col-md-3 form-label">Menü Yönetimi</div>
								<div class="col-md-9 custom-controls-stacked">
									<label class="custom-control custom-checkbox">
										<input type="checkbox" class="custom-control-input" name="ust_menu" value="1">
										<span class="custom-control-label">Üst Menüde Görünsün</span>
									</label>
									<label class="custom-control custom-checkbox">
										<input type="checkbox" class="custom-control-input" name="alt_menu" value="1">
										<span class="custom-control-label">Alt Menüde Görünsün</span>
									</label>
								</div>
							</div>

							<div class="form-group row">
								<div class="col-md-12 form-label">Açıklama</div>
								<div class="col-md-12">
									<textarea class="form-control" id="editor" rows="3" name="aciklama"><?php echo @$duzenle['aciklama']; ?></textarea>
								</div>
							</div>

							<div class="form-group row">
				                <div class="col-md-3">
				                    <div class="uploaddis aktif" data-id="1" style="float:left;">
				        			  <div class="yuklendi">
				        				  <img src="">
				        				  <div class="icon" data-id="1"><span class="fa fa-trash"></span></div>
				        				  <input type="hidden" name="img1" value="" required="">
				        			  </div>
				        			  <div class="upload">
				        				  <span class="metin" style="width: 100%;float: left;">Resim Yükle</span>
				        				  <div class="icon"><span class="fa fa-upload" data-id="1"></span></div>
				        			  </div>
				        			</div>
				                </div>
								<label class="col-md-9 form-label">
									<input type="text" class="form-control" id="url" name="" value="" placeholder="Resim Url Adresi">
								</label>
				            </div>

							<div class="form-group row">
								<div class="col-md-12"><center><button type="submit" class="btn btn-info">Kaydet</button></center></div>
							</div>

				            <div id="queue"></div>

						</form>

					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script type="text/javascript" src="assets/js/jquery.nestable.js"></script>
<link rel="stylesheet" type="text/css" href="assets/css/nestable.css">
<script>
$(document).ready(function(){

    var updateOutput = function(e){
        var list   = e.length ? e : $(e.target),
            output = list.data('output');
        if (window.JSON) {
            output.val(window.JSON.stringify(list.nestable('serialize')));
        } else {
            output.val('JSON browser support required for this demo.');
        }
    };

    $('#nestable').nestable({
        group: 1
    }).on('change', updateOutput);

    updateOutput($('#nestable').data('output', $('#nestable-output')));

});
</script>

<script src="assets/ckeditor/ckeditor.js"></script>
<script src="assets/ckeditor/samples/js/sample.js"></script>
<script>
	initSample();
</script>