<?php

/*======================================================================*\
|| #################################################################### ||
|| # Drag'nDrop Shop 1.8                                              # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright 2014 JAKWEB All Rights Reserved.                       # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| #   ----------- Drag'nDrop Shop IS NOT FREE SOFTWARE -----------   # ||
|| #                      http://www.jakweb.ch                        # ||
|| #################################################################### ||
\*======================================================================*/

// Check if the file is accessed only via index.php if not stop the script from running
if (!defined('JAK_ADMIN_PREVENT_ACCESS')) die('You cannot access this file directly.');

// Check if the user has access to this file
if (!JAK_USERID || !JAK_SUPERADMINACCESS) jak_redirect(BASE_URL);

// All the tables we need for this plugin
$errors = array();
$jaktable = DB_PREFIX.'categories';

// We need that for all
$sqlc = 'SELECT * FROM '.$jaktable.' ORDER BY catorder ASC';
$resultc = $jakdb->query($sqlc);
while ($rowc = $resultc->fetch_assoc()) {
        // collect each record into $_data
        $jakdata[] = $rowc;
    }

$JAK_CAT = $jakdata;

// Now start with the plugin use a switch to access all pages
switch ($page1) {

	case 'sub':
		
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		        $defaults = $_POST;
		        
		         if (isset($defaults['real_cat_id'])) {
		        
		            $categories = $defaults['corder'];
		            $catid = $defaults['real_cat_id'];
		            $realid = implode(',', $defaults['real_cat_id']);
		            $test = array_combine($catid, $categories);
		                
		                foreach ($test as $key => $category) {
		                $updatesql .= sprintf("WHEN %d THEN %d ", $key, $category);
		            	}
		            	
		            	$sql = 'UPDATE '.$jaktable.' SET catorder = CASE id
		        		'.$updatesql.'
		        		END
						WHERE id IN ('.$realid.')';
		                $result = $jakdb->query($sql);
		                
		                if (!$result) {
							jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
						} else {
						
							// Now let us delete the stuff cache file
							$cachestufffile = '../'.JAK_CACHE_DIRECTORY.'/stuff.php';
							if (file_exists($cachestufffile)) {
								unlink($cachestufffile);
							}
				
			        		jak_redirect(BASE_URL.'index.php?p=success');
		        		}
		    	} 
		    }
		
			// Call the template
			$template = 'subcategories.php';
		
	break;
	case 'newcat':
		
		// Additional DB Information
		$jakfield = 'varname';
		
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		    $defaults = $_POST;
		
		    if (empty($defaults['jak_name'])) {
		        $errors['e1'] = $tl['error']['e7'];
		    }
		        
		    if (count($errors) == 0) {
		    
		    if ($defaults['jak_catparent']) {
		    
		    	$sqladd = 'catparent = "'.$defaults['jak_catparent'].'",';
		    	
		    	// Update categories table so if any sub-sub exist move them with the new sub menu
		    	$sql2 = 'UPDATE '.$jaktable.' SET subexist = 1 WHERE id = "'.smartsql($defaults['jak_catparent']).'"';
		    	$result2 = $jakdb->query($sql2);
		    	
		    }
		    
		    if (!empty($defaults['jak_img'])) {
		    	$catimg = 'catimg = "'.$defaults['jak_img'].'",';
		    } else {
		    	$catimg = '';
		    }
		
			$sql = 'INSERT INTO '.$jaktable.' SET 
			name = "'.smartsql($defaults['jak_name']).'",
			varname = "'.JAK_base::jakCleanurl($defaults['jak_name']).'",
			'.$sqladd.$catimg.'
			catorder = 4';
			$result = $jakdb->query($sql);
		
		if (!$result) {
		    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
			} else {
			
				// Now let us delete the stuff cache file
				$cachestufffile = '../'.JAK_CACHE_DIRECTORY.'/stuff.php';
				if (file_exists($cachestufffile)) {
					unlink($cachestufffile);
				}
				
		        jak_redirect(BASE_URL.'index.php?p=success');
		    }
		 } else {
		    
		   	$errors['e'] = $tl['error']['e'];
		    $errors = $errors;
		    }
		}
		
		// Call the template
		$template = 'newcat.php';
		
	break;
	default:
	
		// Additional DB Information
		$jakfield = 'catparent';

		if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($page1)) {
        $defaults = $_POST;
        
                $categories = $defaults['corder'];
                $catid = $defaults['real_cat_id'];
                $realid = implode(',', $defaults['real_cat_id']);
                $test = array_combine($catid, $categories);
                
                foreach ($test as $key => $category) {
                $updatesql .= sprintf("WHEN %d THEN %d ", $key, $category);
            	}
            	
            	$sql = 'UPDATE '.$jaktable.' SET catorder = CASE id
        		'.$updatesql.'
        		END
				WHERE id IN ('.$realid.')';
                $result = $jakdb->query($sql);
                
                if (!$result) {
					jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
				
					// Now let us delete the stuff cache file
					$cachestufffile = '../'.JAK_CACHE_DIRECTORY.'/stuff.php';
					if (file_exists($cachestufffile)) {
						unlink($cachestufffile);
					}
			
	        		jak_redirect(BASE_URL.'index.php?p=success');
    			}     
    }
 
 	switch ($page1) {
 	case 'delete':

	if (jak_row_exist($page2,$jaktable) && $page2 != 1) {
	
		$sql = 'SELECT catparent FROM '.$jaktable.' WHERE id = "'.smartsql($page2).'" LIMIT 1';
		$result = $jakdb->query($sql);
		$row = $result->fetch_assoc();
		
		// Finally delete the category
		$sql = 'DELETE FROM '.$jaktable.' WHERE id = '.smartsql($page2).'';
		$result = $jakdb->query($sql);
		
		// Now if exist do the dirty work find some others and update the database
		if ($row['catparent'] > 0) {
		
			// The sql query
			$sql1 = 'SELECT id FROM '.$jaktable.' WHERE catparent = "'.smartsql($row['catparent']).'" LIMIT 1';
			$result1 = $jakdb->query($sql1);
			while ($jakdb->affected_rows == 0) {
			
				// Update categories table so if any sub-sub exist move them with the new sub menu
			    $sql2 = 'UPDATE '.$jaktable.' SET subexist = 0 WHERE id = "'.smartsql($row['catparent']).'"';
			    $result2 = $jakdb->query($sql2);
			    
			}
		
		}
	
	if (!$result) {
	    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
		} else {
	        jak_redirect(BASE_URL.'index.php?p=success');
	    }
	    
	} else {
		jak_redirect(BASE_URL.'index.php?p=error&sp=cat-no-delete');
		exit;
	}
		break;
		case 'edit':
			
			if (jak_row_exist($page2,$jaktable)) {
	
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			    $defaults = $_POST;
			
			    if (empty($defaults['jak_name'])) {
			        $errors['e1'] = $tl['error']['e7'];
			    }
			        
			    if (count($errors) == 0) {
			    
			    if ($defaults['jak_catparent'] != $defaults['jak_catparent_old']) {
			    
			    	if ($defaults['jak_subexist']) {
				    
				    	$jakdb->query('UPDATE '.$jaktable.' SET catparent = "'.$defaults['jak_catparent'].'", catparent2 = "'.smartsql($page2).'" WHERE catparent = "'.smartsql($page2).'"');
				    	
				    		if ($defaults['jak_catparent'] != 0) { 
				    			$jakdb->query('UPDATE '.$jaktable.' SET subexist = 1 WHERE id = "'.$defaults['jak_catparent'].'"');
				    		}
				    		
				    		if (jak_field_not_exist($defaults['jak_catparent_old'], $jaktable, 'catparent')) {
				    		
				    			$jakdb->query('UPDATE '.$jaktable.' SET subexist = 0 WHERE id = "'.$defaults['jak_catparent_old'].'"');
				    		}
				    		
				    		$include = 'subexist = 0,';
				    
				    
				    } else {
				    
				    	if ($defaults['jak_catparent'] != 0) { 
				    		$jakdb->query('UPDATE '.$jaktable.' SET subexist = 1 WHERE id = "'.$defaults['jak_catparent'].'"');
				    	}
				    	
				    	if (jak_field_not_exist($defaults['jak_catparent_old'], $jaktable, 'catparent')) {
				    	
				    		$jakdb->query('UPDATE '.$jaktable.' SET subexist = 0 WHERE id = "'.$defaults['jak_catparent_old'].'"');
				    	}
				    }
			    		    
			    	$include .= 'catparent = "'.$defaults['jak_catparent'].'",';
			    
			    }
			    
			    
			    if (!empty($defaults['jak_img'])) {
			    	$include .= 'catimg = "'.$defaults['jak_img'].'",';
			    } else {
			    	$include .= 'catimg = NULL,';
			    }
			
				$sql = 'UPDATE '.$jaktable.' SET 
				'.$include.'
				name = "'.smartsql($defaults['jak_name']).'",
				varname = "'.JAK_base::jakCleanurl($defaults['jak_name']).'"
				WHERE id = "'.smartsql($page2).'"';
				$result = $jakdb->query($sql);
			
				if (!$result) {
			    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
				
					// Now let us delete the stuff cache file
					$cachestufffile = '../'.JAK_CACHE_DIRECTORY.'/stuff.php';
					if (file_exists($cachestufffile)) {
						unlink($cachestufffile);
					}
					
			        jak_redirect(BASE_URL.'index.php?p=success');
			    }
			 } else {
			   	$errors['e'] = $tl['error']['e'];
			    $errors = $errors;
			 }
	}
	
	// Get the data
	$JAK_FORM_DATA = jak_get_data($page2, $jaktable);
	
	$template = 'editcat.php';
	
	} else {
	    
	   	jak_redirect(BASE_URL.'index.php?p=error&sp=cat-not-exist');
	}
	
	break;
	default:
		// Call the template
		$template = 'categories.php';
		
	}
}
?>