<?php

/**
 * @author Pratik Dev <webmaster.pratik@gmail.com>
 */
header('Content-Type: application/json; charset=utf-8');
function WriteNavigation()
{
	global $db, $RootPath;
	$data = $db->where('status', 1)->where('parentid', 0)->orderBy('pos', 'ASC')->orderBy('id')->get(TABLE_CAT, null, 'name,slug');
	$catLink = '';
	foreach ($data as $d) {
		$catLink .= '<li><a class="dropdown-item" href="' . APP_URL . '/category/' . $d['slug'] .ROUTE_END. '">' . $d['name']. '</a></li>';
	}
	WriteFile($RootPath . '/templates/' . TEMPLATE . '/_navbar.php', $catLink);
}
require_once '../config/init.php';
$currentAction = Input('submit');
if ($currentAction == 'list') {
	$searchValue = dtsValue();
	if ($searchValue) {
		$db->where('name', '%' . $searchValue . '%', 'LIKE');
	}
	if (InputArray('order')) {
		$column = dtOrderby();
		if ($column == 2)
			$db->orderBy('name', dtOrderby(false));
		else
			$db->orderBy('id', dtOrderby(false));
	} else {
		$db->orderBy('pos', 'ASC');
		$db->orderBy('id');
	}
	if (Input('parentid')) {
		$db->where('parentid', Input('parentid'));
	} else {
		$db->where('parentid', 0);
	}
	if (Input('length') != -1) {
		$categories = $db->withTotalCount()->get(TABLE_CAT, array(dtlimit(), dtlimit(false)));
	} else {
		$categories = $db->withTotalCount()->get(TABLE_CAT);
	}
	$numRows = $db->totalCount;
	$data = array();

	$size = explode(',', CATICON_SIZES);

	foreach ($categories as $cat) {
		$row = array();
		$action = '';
		if ($cat['subcate'] == '0') {
			$action .= '<a href="../files/create.php?cid=' . $cat["id"] . '" class="btn btn-primary btn-sm m-2"><i class="fas fa-upload"></i></a>';
			$action .= '<a href="../files/multi.php?cid=' . $cat["id"] . '" class="btn btn-primary btn-sm m-2"><i class="fas fa-cloud-upload-alt"></i></a>';
		}
		if ($cat['subcate'] > 0 || $cat['totalitem'] == '0') {
			$action .= '<button type="button" name="addcatTo" id="' . $cat["id"] . '" data-name="' . $cat['name'] . '" class="addcatTo btn btn-info btn-sm m-2"><i class="fas fa-folder-plus"></i></button>';
			$action .= '<button type="button" name="addcatTo" id="' . $cat["id"] . '" data-name="' . $cat['name'] . '" class="addAlbumTo btn btn-info btn-sm m-2"><i class="fas fa-film"></i></button>';
		}
		if ($cat['totalitem'] > 0 && $cat['subcate'] == 0) {
			$catLink = '../files/index.php?cid=' . $cat['id'];
		} else {
			$catLink = '?parentid=' . $cat['id'];
		}
		if ($cat['thumb'] != "") {
			$thumb = '<img class="border border-dark" src="../../upload_file/folderthumb/' . $size[0] . '/' . $cat['thumb'] . '" alt="Icon" width="60" height="60">';
		} else {
			$thumb = '';
		}
		$catType = ($cat['is_cat'] == 1) ? '<span class="badge bg-warning text-light">Category</span>' : '<span class="badge bg-primary text-light">Album</span>';
		$action .= '<button type="button" name="edit" id="' . $cat["id"] . '" class="edit btn btn-success btn-sm m-2"><i class="fas fa-edit"></i></button><button type="button" name="delete" id="' . $cat["id"] . '" class="delete btn btn-danger btn-sm m-2"><i class="fas fa-trash-alt"></i></button>';
		$row[] = $cat['id'];
		$row[] = $thumb;
		$row[] = '<a href="' . $catLink . '">' . $cat['name'] . '</a><br>Total Files: ' . $cat['totalitem'];
		$row[] = $catType;
		$row[] = $cat['pos'];
		$row[] = ($cat['status'] == true) ? '<span id="' . $cat['id'] . '" class="status btn btn-success btn btn-sm m-2">Active</span>' : '<span id="' . $cat['id'] . '" class="status btn btn-warning btn-sm m-2">Block</span>';
		$row[] = $action;
		$data[] = $row;
	}
	$output = array(
		"draw"				=>	intval(Input('draw')),
		"recordsTotal"  	=>  $numRows,
		"recordsFiltered" 	=> 	$numRows,
		"data"    			=>   $data
	);
	echo json_encode($output);
} else if ($currentAction == 'delete') {
	$id = Input('id');
	$category = $db->where('id', $id)->getOne(TABLE_CAT);
	if ($category) {
		if ($category['parentid'] != 0) {
			$db->where('id', $category['parentid'])->update(TABLE_CAT, ['subcate' => $db->dec(1)]);
		}
		deleteCatThumb($category['thumb']);

		$catFolder = rtrim($category['folder'], '/');
		$deldir = $RootPath . '/' . $catFolder;
		if ($catFolder) {
			if (is_dir($deldir))
				rmdirr($deldir);
		}
		deleteSubCat($id);
		$parentids = array_filter(explode('/', $category['folder']));
		array_shift($parentids);
		//array_pop($parentids);
		if ($parentids) {
			$db->where('id', $parentids, 'IN')->update(TABLE_CAT, ['totalitem' => $db->dec($category['totalitem'])]);
		}
		$db->where('id', $id)->delete(TABLE_CAT);
		$db->where('cid', $id)->delete(TABLE_FILES);
		WriteNavigation();
		$data = [
			'status' => 1,
			'message' => 'Category Delete Successfuly'

		];
	} else {
		$data = [
			'status' => 0,
			'message' => 'Category Delete Unsuccessfuly'

		];
	}
	echo json_encode($data);
} else if ($currentAction == 'getOne') {
	$db->where('id', Input('id'));
	$catInfo = $db->getOne(TABLE_CAT);
	$size = explode(',', CATICON_SIZES);

	if ($catInfo['thumb'] != '') {
		$thumbnail = '../../upload_file/folderthumb/' . $size[0] . '/' . $catInfo['thumb'];
	} else {
		$thumbnail = '';
	}
	$data = [
		'id' => $catInfo['id'],
		'name' => $catInfo['name'],
		'pos' => $catInfo['pos'] ? $catInfo['pos'] : 0,
		'thumb' => $thumbnail,
		'slug' => $catInfo['slug'],
		'description' => $catInfo['des'],
		'status' => $catInfo['status'],
		'meta_title' => $catInfo['meta_title'],
		'meta_keyw' => $catInfo['meta_keyw'],
		'meta_des' =>  $catInfo['meta_des'],
		'added_home' => $catInfo['added_home'],
		'newtag' => $catInfo['newitemtag'],
		'updatetag' => $catInfo['updateitemtag'],
		'is_cat' => $catInfo['is_cat'],
		'release_year' => $catInfo['release_year']
	];
	echo json_encode($data);
} else if ($currentAction == 'create' || $currentAction == "edit") {
	if (empty(Input('category_name'))) {

		$data = [
			'status' => 2,
			'message' => 'Please Fill Fill Category Name'

		];

		echo json_encode($data);
		exit;
	}

	$parentid = Input('parentid') ? Input('parentid') : 0;
	if ($parentid != 0) {
		$db->where('id', $parentid)->update(TABLE_CAT, ['subcate' => $db->inc(1)]);
	}

	$categoryUpdate = false;

	$createType = Input('create_type') ? 1 : 0;

	if (Input('id')) {
		$id = Input('id');
		$category = $db->where('id', $id)->getOne(TABLE_CAT);
		$catSlug = Input('slug') ? Input('slug') : genSlug(Input('category_name'));
		$oldslug = ($catSlug != $category['slug']) ? $category['slug'] : '';
		$sqlData = [
			'parentid' => $parentid,
			'name' => Input('category_name'),
			'release_year' => ($createType != 1) ? Input('release_year') : '',
			'totalitem' => $category['totalitem'],
			'newitemtag' => Input('newtag') ? 1 : 0,
			'updateitemtag' => Input('updatetag') ? 1 : 0,
			'subcate' =>  $category['subcate'],
			'des' => ($createType == 1) ? str_replace(array('<p><br></p>', '<p></p>'), '', Input('category_des', true)) : '',
			'slug' => $catSlug,
			'old_slug' => $oldslug,
			'pos' => Input('category_order') ? Input('category_order') : 0,
			'meta_title' => Input('meta_title'),
			'meta_keyw' => Input('meta_keyw'),
			'meta_des' => Input('meta_des'),
			'added_home' => Input('added_home') ? 1 : 0,
			'is_cat' => $createType,
			'status' => Input('status') ? 1 : 0
		];
		$db->where('id', $id)->update(TABLE_CAT, $sqlData);
		$categoryUpdate = true;
	} else {
		$sqlData = [
			'parentid' => $parentid,
			'name' => Input('category_name'),
			'release_year' => ($createType != 1) ? Input('release_year') : '',
			'totalitem' => 0,
			'newitemtag' => Input('newtag') ? 1 : 0,
			'updateitemtag' => Input('updatetag') ? 1 : 0,
			'subcate' => 0,
			'des' => ($createType == 1) ? str_replace(array('<p><br></p>', '<p></p>'), '', Input('category_des', true)) : '',
			'slug' => Input('slug') ? Input('slug') : genSlug(Input('category_name')),
			'pos' => Input('category_order') ? Input('category_order') : 0,
			'meta_title' => Input('meta_title'),
			'meta_keyw' => Input('meta_keyw'),
			'meta_des' => Input('meta_des'),
			'added_home' => Input('added_home') ? 1 : 0,
			'is_cat' => $createType,
			'created_at' => $db->now(),
			'status' => Input('status') ? 1 : 0
		];

		$id = $db->insert(TABLE_CAT, $sqlData);
	}
	if ($id) {
		$category = $db->where('id', $id)->getOne(TABLE_CAT);
		if ($parentid == 0) {
			$folder = 'upload_file/' . $id . '/';
			if (!is_dir($RootPath . '/upload_file/' . $id))
				mkdir($RootPath . '/upload_file/' . $id, 0777, true);
		} else {
			$folder = $db->where('id', $parentid)->getValue(TABLE_CAT, 'folder');

			if (!is_dir($RootPath . '/' . $folder . $id))
				mkdir($RootPath . '/' . $folder . $id, 0777, true);

			$folder = $folder . $id . '/';
		}

		$db->where('id', $id)->update(TABLE_CAT, ['folder' => $folder]);

		$thumbnailname = '';

		$w_pos = Input('w_pos') ? Input('w_pos') : 'top-left';
		$saveToThumb = $RootPath . '/upload_file/folderthumb/';
		$thumbfrom = Input('thumbfrom');
		if ($thumbfrom == 'EXTERNAL_LINK') {
			$thumbURL = trim(Input('thumb_url'));
			$thumb_ext = pathinfo($thumbURL, PATHINFO_EXTENSION);

			if ($thumbURL && $thumb_ext) {
				$tmp_thumbname = 'tmp_thumb.' . $thumb_ext;
				$thumbnailname = $category['thumb'] ? pathinfo($category['thumb'], PATHINFO_FILENAME) : uniqid('thumb_');
				$saveThumb = $RootPath . '/upload_file/folderthumb/' . $tmp_thumbname;
				if (urlCopy($thumbURL, $saveThumb)) {
					genThumb($saveThumb, $saveToThumb, $thumbnailname, $w_pos, true);
					unlink($saveThumb);
				}
			}
		} else {
			if ($_FILES['thumb']['name']) {
				$thumbnailname = $category['thumb'] ? pathinfo($category['thumb'], PATHINFO_FILENAME) : uniqid('thumb_');
				genThumb($_FILES['thumb']['tmp_name'], $saveToThumb, $thumbnailname, $w_pos, true);
			}
		}

		$upcatdata = [
			'thumb' => $thumbnailname ? $thumbnailname . '.' . THUMB_FORMAT : $category['thumb'],
		];
		$db->where('id', $id)->update(TABLE_CAT, $upcatdata);
		WriteNavigation();
		if ($categoryUpdate == true) {
			$data = [
				'status' => 1,
				'message' => 'Category Update Successfuly'

			];
		} else {
			$data = [
				'status' => 1,
				'message' => 'Category Added Successfuly'

			];
		}
	} else {
		$data = [
			'status' => 0,
			'message' => $db->getLastError()

		];
	}
	echo json_encode($data);
} else if ($currentAction == "removethumb") {
	if ($id = Input('id')) {
		$category = $db->where('id', $id)->getOne(TABLE_CAT);
		$thumbnailname = $category['thumb'];
		if ($thumbnailname) {
			$saveTo = $RootPath . '/upload_file/folderthumb';
			$appsizes = explode(',', CATICON_SIZES);
			foreach ($appsizes as $wh) {
				$Imgwh = explode('x', $wh);
				$ImgDir = $saveTo . '/' . $wh;
				if (file_exists($ImgDir . '/' . $thumbnailname))
					unlink($ImgDir . '/' . $thumbnailname);
			}
			$newthumbname = pathinfo($thumbnailname, PATHINFO_FILENAME);
			$catCover = $RootPath . '/upload_file/folderthumb/' . MP3TAG_COVER . '/cover_' . pathinfo($category['thumb'], PATHINFO_FILENAME) . '.jpg';
			if (file_exists($catCover)) {
				unlink($catCover);
			}
		}
		$db->where('id', $id)->update(TABLE_CAT, ['thumb' => '']);
	}
	echo json_encode([
		'status' => 1,
		'message' => 'Thumbnail Removed'

	]);
} elseif ($currentAction == "statusUpdater") {

	$id = Input('id');
	$status = $db->where('id', $id)->getValue(TABLE_CAT, 'status');

	if ($status == 1) {
		$data = ['status' => 0];
	} else {
		$data = ['status' => 1];
	}
	$db->where('id', $id)->update(TABLE_CAT, $data);
	WriteNavigation();
	echo json_encode([
		'status' => 1,
		'message' => 'Status Updated'

	]);
} elseif ($currentAction == "slugcheck") {

	$id = Input('id');
	$slug = Input('slug');
	$slug = genSlug($slug, $id, false);

	echo json_encode([
		'status' => 1,
		'slug' => $slug,
	]);
} else if ($currentAction == "multipledelete") {
	$ids = InputArray('ids');
	if (!$ids) {
		echo json_encode(['status' => 0, 'message' => 'Sorry No item Selected or Target Category Id Missing']);
		exit;
	}
	$cnt = 0;
	foreach ($ids as $id) {
		$category = $db->where('id', $id)->getOne(TABLE_CAT);
		if (!$category) {
			continue;
		}
		if ($category['parentid'] != 0) {
			$db->where('id', $category['parentid'])->update(TABLE_CAT, ['subcate' => $db->dec(1)]);
		}
		deleteCatThumb($category['thumb']);
		$catFolder = rtrim($category['folder'], '/');
		$deldir = $RootPath . '/' . $catFolder;
		if ($catFolder) {
			if (is_dir($deldir))
				rmdirr($deldir);
		}

		deleteSubCat($id);
		$parentids = array_filter(explode('/', $category['folder']));
		array_shift($parentids);
		//array_pop($parentids);
		if ($parentids) {
			$db->where('id', $parentids, 'IN')->update(TABLE_CAT, ['totalitem' => $db->dec($category['totalitem'])]);
		}
		$db->where('id', $id)->delete(TABLE_CAT);
		$db->where('cid', $id)->delete(TABLE_FILES);
		$cnt++;
	}
	WriteNavigation();
	echo json_encode(['status' => 1, 'message' => 'Total: ' . $cnt . ' Deleted Successfuly']);
	exit;
} else  if ($currentAction == 'MoveFiles') {
	$ids = InputArray('ids');
	$targetId = Input('targetId');
	if (!$ids || $targetId == null) {
		echo json_encode([
			'status' => 0,
			'message' => 'No Item Selected or Target Category Id Missing'

		]);
		exit;
	}
	if ($targetId != 0) {
		$catinfo = $db->where('id', $targetId)->getOne(TABLE_CAT);
		if (!$catinfo) {
			echo json_encode(['status' => 0, 'message' => 'Target category not found']);
			exit;
		}

		if ($catinfo['totalitem'] > 0 && $catinfo['subcate'] == 0) {
			echo json_encode(['status' => 0, 'message' => 'Target category not Parent']);
			exit;
		}

		$targetFolder = rtrim($catinfo['folder'], '/');
		if (!$targetFolder) {
			echo json_encode(['status' => 0, 'message' => 'Target category found but folder not found']);
			exit;
		}
	} else {
		$targetFolder = 'upload_file';
	}
	$cnt = 0;
	foreach ($ids as $id) {
		if (!$id) {
			continue;
		}
		$category = $db->where('id', $id)->getOne(TABLE_CAT);
		if (!$category) {
			continue;
		}
		if ($targetId == $category['id']) {
			continue;
		}
		$catFolder = rtrim($category['folder'], '/');
		$movefolder = $RootPath . '/' . $catFolder;
		$mvtarget = $RootPath . '/' . $targetFolder . '/' . $category['id'];
		if ($catFolder) {
			if (is_dir($movefolder)) {
				MoveFolderFiles($movefolder, $mvtarget, true);
			}
		}
		//Update Current Folder Path
		$newfolderpath = $targetFolder . '/' . $category['id'] . '/';
		$db->where('id', $id)->update(TABLE_CAT, ['parentid' => $targetId, 'folder' => $newfolderpath]);
		MoveSubFolder($id, array_replace($category, ['folder' => $newfolderpath]));
		// Decrement 
		$parentids = array_filter(explode('/', $category['folder']));
		array_shift($parentids);
		if ($parentids) {
			$db->where('id', $parentids, 'IN')->update(TABLE_CAT, ['totalitem' => $db->dec($category['totalitem'])]);
		}
		// Increment
		$parentidsInc = array_filter(explode('/', $newfolderpath));
		array_shift($parentidsInc);
		if ($parentidsInc) {
			$db->where('id', $parentidsInc, 'IN')->update(TABLE_CAT, ['totalitem' => $db->inc($category['totalitem'])]);
		}
		if ($category['parentid'] != 0) {
			$db->where('id', $category['parentid'])->update(TABLE_CAT, ['subcate' => $db->dec(1)]);
		}
		if ($targetId != 0) {
			$db->where('id', $targetId)->update(TABLE_CAT, ['subcate' => $db->inc(1)]);
		}
		$cnt++;
	}
	WriteNavigation();
	echo json_encode(['status' => 1, 'message' => 'Total: ' . $cnt . ' Category Moved']);
}
