<?php

/**
 * @author Pratik Dev <webmaster.pratik@gmail.com>
 */
header('Content-Type: application/json; charset=utf-8');

use Intervention\Image\ImageManagerStatic as Image;
use Intervention\Image\Exception\NotReadableException;

require_once '../config/init.php';
$currentAction = Input('submit');
if ($currentAction == 'list') {
	$db->join(TABLE_CAT, '' . TABLE_CAT . '.id=' . TABLE_FILES . '.cid', "INNER");
	$db->join('users u', '' . TABLE_FILES . '.user_id=u.id', "LEFT");
	$searchValue = dtsValue();
	if ($searchValue) {
		$db->where(TABLE_FILES . '.name', '%' . $searchValue . '%', 'LIKE');
	}
	if (InputArray('order')) {
		$column = dtOrderby();
		if ($column == 2)
			$db->orderBy(TABLE_FILES . '.name', dtOrderby(false));
		else if ($column == 8)
			$db->orderBy(TABLE_FILES . '.download', dtOrderby(false));
		else if ($column == 9)
			$db->orderBy(TABLE_FILES . '.pos', dtOrderby(false));
		else if ($column == 10)
			$db->orderBy(TABLE_FILES . '.approved_at', dtOrderby(false));
		else if ($column == 11)
			$db->orderBy(TABLE_FILES . '.deleted_at', dtOrderby(false));
		else {
			$db->orderBy(TABLE_FILES . '.id', dtOrderby(false));
		}
	} else {
		$db->orderBy(TABLE_FILES . '.pos', 'ASC');
		$db->orderBy(TABLE_FILES . '.id');
	}

	if (Input('filterdata') == "TRASHED") {
		$db->where(TABLE_FILES . '.deleted_at', NULL, 'IS NOT');
	} else {
		$db->where(TABLE_FILES . '.deleted_at', NULL, 'IS');
	}

	if (Input('filterdata') == "PENDING") {
		$db->where(TABLE_FILES . '.approved_at', NULL, 'IS');
	} else {
		$db->where(TABLE_FILES . '.approved_at', NULL, 'IS NOT');
		//$db->where('(' . TABLE_FILES . '.approved_at IS NOT NULL OR ' . TABLE_FILES . '.user_id="0")');
	}


	if (Input('parentid')) {
		$db->where(TABLE_FILES . '.cid', Input('parentid'));
	}

	if (Input('userid')) {
		$db->where(TABLE_FILES . '.user_id', Input('userid'));
	}

	$selectData = TABLE_FILES . '.*,' . TABLE_CAT . '.name as category_name,' . TABLE_CAT . '.folder,u.name as user_fullname,u.user_name';

	if (Input('length') != -1) {
		$files = $db->withTotalCount()->get(TABLE_FILES, array(dtlimit(), dtlimit(false)), $selectData);
	} else {
		$files = $db->withTotalCount()->get(TABLE_FILES, null, $selectData);
	}
	$numRows = $db->totalCount;
	$data = array();
	$size = explode(',', FILE_THUMB_SIZES);

	foreach ($files as $file) {
		$row = array();
		$action = '';
		if ($file['thumb'] != "") {
			$thumb = '<img class="border border-dark" src="../../' . $file['folder'] . $size[0] . '/' . $file['thumb'] . '" alt="Icon" width="60" height="60">';
		} else {
			$thumb = '';
		}
		$action .= '<div class="dropdown">
		<button class="btn btn-danger btn-sm m-2 dropdown-toggle" type="button" id="dropdownDelete" data-toggle="dropdown" aria-expanded="false">
			...
		</button>
		<div class="dropdown-menu" aria-labelledby="dropdownDelete">';

		if (!$file['approved_at'] && $file['user_id'] != 0) {
			$action .= '<a class="text-success approve dropdown-item" href="#">Approve</a>';
		}


		$action .=
			'<a id="' . $file['id'] . '" class="text-info dropdown-item" href="edit.php?id=' . $file['id'] . '">Edit</a>
			 <a id="' . $file['id'] . '" class="text-danger delete dropdown-item" href="#">Delete</a>';

		if ($file['deleted_at']) {
			$action .= '<a id="' . $file['id'] . '" class="text-warning restore dropdown-item" href="#">Restore</a>';
		} else
			$action .= '<a id="' . $file['id'] . '" class="text-warning trash dropdown-item" href="#">Trash</a>';

		$action .= '<a id="' . $file['id'] . '" class="text-success changetag dropdown-item" href="">Change Tag</a>';

		$action .=		'</div>
	</div>';
		$row[] = $file['id'];
		$row[] = $thumb;
		$row[] = $file['name'];
		$row[] = ($file['user_name']) ? '<a href="../user/show.php?id=' . $file['user_id'] . '">' . $file['user_name'] . '</a>' : "Admin";
		$row[] = '<a href="?cid=' . $file['cid'] . '">' . $file['category_name'] . '</a>';
		$row[] = $file['artist'];
		$row[] = strtoupper($file['ext']);
		$row[] = formatSize($file['size']);
		$row[] = $file['download'];
		$row[] = $file['pos'];
		$row[] = ($file['approved_at']) ? date('M d, y', strtotime($file['approved_at'])) : '';
		$row[] = ($file['deleted_at']) ? date('M d, y', strtotime($file['deleted_at'])) : '';
		$row[] = ($file['status'] == true) ? '<span id="' . $file['id'] . '" class="status btn btn-success btn btn-sm m-2">Active</span>' : '<span id="' . $file['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);
} elseif ($currentAction == "statusUpdater") {

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

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

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

	$id = Input('id');
	$file = $db->where('id', $id)->getOne(TABLE_FILES);
	$category = $db->where('id', $file['cid'])->getOne(TABLE_CAT);

	if (!$category && !$file) {
		echo json_encode([
			'status' => 2,
			'message' => 'Delete File'

		]);
		exit;
	}

	$parentids = array_filter(explode('/', $category['folder']));
	array_shift($parentids);
	if ($parentids) {
		$db->where('id', $parentids, 'IN')->update(TABLE_CAT, ['totalitem' => $db->dec(1)]);
	}

	$extension = pathinfo($file['dname'], PATHINFO_EXTENSION);
	$filename = $extension ? $file['dname'] : $file['dname'] . '.' . $file['ext'];
	$Path = $RootPath . '/' . $category['folder'] . $filename;
	$thumbname = $file['thumb'];
	if ($thumbname) {
		$appsizes = explode(',', FILE_THUMB_SIZES);
		foreach ($appsizes as $wh) {
			$Imgwh = explode('x', $wh);
			$ImgDir =  $RootPath . '/' . $category['folder'] . $wh;
			if (file_exists($ImgDir . '/' . $thumbname))
				unlink($ImgDir . '/' . $thumbname);
		}

		$cover = $RootPath . '/' . $category['folder'] . MP3TAG_COVER . '/cover_' . pathinfo($thumbname, PATHINFO_FILENAME) . '.jpg';
		if (file_exists($cover)) {
			unlink($cover);
		}
	}
	if (file_exists($Path)) {
		unlink($Path);
	}

	$db->where('id', $id)->delete(TABLE_FILES);
	echo json_encode([
		'status' => 1,
		'message' => 'Deleted Successfuly'

	]);
} else if ($currentAction == "removethumb") {
	if ($id = Input('id')) {
		$file =  $db->where('id', $id)->getOne(TABLE_FILES);
		$category = $db->where('id', $file['cid'])->getOne(TABLE_CAT);
		$thumbname = $file['thumb'];
		if ($thumbname) {
			$appsizes = explode(',', FILE_THUMB_SIZES);
			foreach ($appsizes as $wh) {
				$Imgwh = explode('x', $wh);
				$ImgDir =  $RootPath . '/' . $category['folder'] . $wh;
				if (file_exists($ImgDir . '/' . $thumbname))
					unlink($ImgDir . '/' . $thumbname);
			}
			$cover = $RootPath . '/' . $category['folder'] . MP3TAG_COVER . '/cover_' . pathinfo($thumbname, PATHINFO_FILENAME) . '.jpg';
			if (file_exists($cover)) {
				unlink($cover);
			}
		}
		$db->where('id', $id)->update(TABLE_FILES, ['thumb' => '']);
	}
	echo json_encode([
		'status' => 1,
		'message' => 'Thumbnail Removed'

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

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

	echo json_encode([
		'status' => 1,
		'slug' => $slug,
	]);
} else if ($currentAction == 'tagsartist') {
	$tag = Input('term');

	if ($tag) {
		$db->where('name', '%' . $tag . '%', 'LIKE');
	}
	$data = $db->get("artist", null, 'name');
	$tags = array();
	foreach ($data as $d) {
		array_push($tags, $d['name']);
	}
	echo json_encode($tags);
} else if ($currentAction == "multipledelete") {
	$ids = InputArray('ids');
	$cnt = 0;
	if ($ids) {
		foreach ($ids as $id) {
			if ($id) {
				$file = $db->where('id', $id)->getOne(TABLE_FILES);
				if (!$file) {
					continue;
				}
				$category = $db->where('id', $file['cid'])->getOne(TABLE_CAT);
				if (!$category) {
					continue;
				}
				$parentids = array_filter(explode('/', $category['folder']));
				array_shift($parentids);
				if ($parentids) {
					$db->where('id', $parentids, 'IN')->update(TABLE_CAT, ['totalitem' => $db->dec(1)]);
				}
				$extension = pathinfo($file['dname'], PATHINFO_EXTENSION);
				$filename = $extension ? $file['dname'] : $file['dname'] . '.' . $file['ext'];
				$Path = $RootPath . '/' . $category['folder'] . $filename;
				$thumbname = $file['thumb'];
				if ($thumbname) {
					$appsizes = explode(',', FILE_THUMB_SIZES);
					foreach ($appsizes as $wh) {
						$Imgwh = explode('x', $wh);
						$ImgDir =  $RootPath . '/' . $category['folder'] . $wh;
						if (file_exists($ImgDir . '/' . $thumbname))
							unlink($ImgDir . '/' . $thumbname);
					}

					$cover = $RootPath . '/' . $category['folder'] . MP3TAG_COVER . '/cover_' . pathinfo($thumbname, PATHINFO_FILENAME) . '.jpg';
					if (file_exists($cover)) {
						unlink($cover);
					}
				}
				if (file_exists($Path)) {
					unlink($Path);
				}

				if ($db->where('id', $id)->delete(TABLE_FILES))
					$cnt++;
			}
		}

		echo json_encode([
			'status' => 1,
			'message' => 'Total ' . $cnt . ' Deleted Successfuly'

		]);
		exit;
	}

	echo json_encode([
		'status' => 0,
		'message' => 'No Item Selected'

	]);
} else if ($currentAction == "MoveFiles") {
	$ids = InputArray('ids');
	$targetid = Input('targetId');
	if (!$ids || !$targetid) {
		echo json_encode([
			'status' => 0,
			'message' => 'No Item Selected or Target Category Id Missing'

		]);
		exit;
	}
	$catinfo = $db->where('id', $targetid)->getOne(TABLE_CAT);

	if (!$catinfo) {
		echo json_encode([
			'status' => 0,
			'message' => 'Target Category Not Found'

		]);
		exit;
	}

	if ($catinfo['subcate'] != 0) {
		echo json_encode([
			'status' => 0,
			'message' => 'Target Category are not a Child'

		]);
		exit;
	}

	$cnt = 0;
	foreach ($ids as $id) {
		if ($id) {
			$file = $db->where('id', $id)->getOne(TABLE_FILES);
			if (!$file) {
				continue;
			}
			$category = $db->where('id', $file['cid'])->getOne(TABLE_CAT);
			if (!$category) {
				continue;
			}

			if ($targetid == $category['id']) {
				continue;
			}

			$parentids = array_filter(explode('/', $category['folder']));
			array_shift($parentids);
			if ($parentids) {
				$db->where('id', $parentids, 'IN')->update(TABLE_CAT, ['totalitem' => $db->dec(1)]);
			}

			$extension = pathinfo($file['dname'], PATHINFO_EXTENSION);
			$filename = $extension ? $file['dname'] : $file['dname'] . '.' . $file['ext'];
			$Path = $RootPath . '/' . $category['folder'] . $filename;
			$NewSavePath = $RootPath . '/' . $catinfo['folder'] . $filename;
			if (file_exists($Path)) {
				rename($Path, $NewSavePath);
			}
			$thumbname = $file['thumb'];
			if ($thumbname) {
				$appsizes = explode(',', FILE_THUMB_SIZES);
				foreach ($appsizes as $wh) {
					$Imgwh = explode('x', $wh);
					$ImgDir =  $RootPath . '/' . $category['folder'] . $wh;
					$ThumbSavePath = $RootPath . '/' . $catinfo['folder'] . $wh;
					if (!is_dir($ThumbSavePath)) {
						mkdir($ThumbSavePath);
					}
					if (file_exists($ImgDir . '/' . $thumbname)) {
						rename($ImgDir . '/' . $thumbname, $ThumbSavePath . '/' . $thumbname);
					}
				}
				$covername = pathinfo($thumbname, PATHINFO_FILENAME) . '.jpg';
				$cover = $RootPath . '/' . $category['folder'] . MP3TAG_COVER . '/cover_' . $covername;
				$coverSaveNew = $RootPath . '/' . $catinfo['folder'] . MP3TAG_COVER . '/cover_' . $covername;
				if (file_exists($cover)) {
					rename($cover, $coverSaveNew);
				}
			}
			$parentidsinc = array_filter(explode('/', $catinfo['folder']));
			array_shift($parentidsinc);
			if ($parentidsinc) {
				$db->where('id', $parentidsinc, 'IN')->update(TABLE_CAT, ['totalitem' => $db->inc(1)]);
			}
			if ($db->where('id', $id)->update(TABLE_FILES, ['cid' => $targetid]))
				$cnt++;
		}
	}

	echo json_encode([
		'status' => 1,
		'message' => 'Total ' . $cnt . ' Moved Successfuly'

	]);
	exit;
} elseif ($currentAction == 'userfilestatus') {

	$ids = InputArray('ids');
	$type = Input('type');

	if (!$ids) {
		echo json_encode(['status' => 0, 'message' => 'Sorry No item Selected']);
		exit;
	}

	if (!in_array($type, ['approveAll', 'restoreAll', 'trashedAll'])) {
		echo json_encode(['status' => 0, 'message' => 'Sorry Invalid Action']);
		exit;
	}
	$cnt = 0;

	switch ($type) {
		case "approveAll":
			$subData = ['approved_at' => $db->now()];
			$title = "Approved";
			//$db->where('approved_at', NULL, 'IS');
			break;
		case "restoreAll":
			$subData = ['deleted_at' => NULL];
			$title = "Restored";
			$db->where('deleted_at', NULL, 'IS NOT');
			break;
		case "trashedAll":
			$subData = ['deleted_at' => $db->now()];
			$title = "Trashed";
			$db->where('deleted_at', NULL, 'IS');
			break;
	}


	foreach ($ids as $id) {
		if (!$id) {
			continue;
		}
		if ($db->where('id', $id)->update(TABLE_FILES, $subData)) {
			$cnt++;
		}
	}
	echo json_encode(['status' => 1, 'message' => 'Total: ' . $cnt . ' Items Successfuly ' . $title]);
} else if ($currentAction == 'getId3') {
	$id = Input('id');
	$file = $db->join(TABLE_CAT . ' c', 'f.cid=c.id', 'INNER')->where('f.id', $id)->getOne(TABLE_FILES . ' f', 'f.id,f.dname,f.ext,c.folder');

	if (!$file) {
		echo json_encode(['status' => 0, 'message' => 'File Not Found']);
		exit;
	}

	$extension = pathinfo($file['dname'], PATHINFO_EXTENSION);
	$filename = $extension ? $file['dname'] : $file['dname'] . '.' . $file['ext'];
	$Path = $RootPath . '/' . $file['folder'] . $filename;
	if (!file_exists($Path)) {
		echo json_encode(['status' => 0, 'message' => 'File Not Found']);
		exit;
	}


	$getID3 = new getID3;
	$ThisFileInfo = $getID3->analyze($Path);
	$getID3->CopyTagsToComments($ThisFileInfo);
	$ThisFileInfo = $ThisFileInfo['tags']['id3v2'];
	echo json_encode(['status' => 1, 'data' => $ThisFileInfo]);

	exit;
} else if ($currentAction == "changeTag") {
	$id = Input('id');
	$file = $db->join(TABLE_CAT . ' c', 'f.cid=c.id', 'INNER')->where('f.id', $id)->getOne(TABLE_FILES . ' f', 'f.id,f.dname,f.ext,c.folder');

	if (!$file) {
		echo json_encode(['status' => 0, 'message' => 'File Not found']);
		exit;
	}

	$extension = pathinfo($file['dname'], PATHINFO_EXTENSION);
	$filename = $extension ? $file['dname'] : $file['dname'] . '.' . $file['ext'];
	$Path = $RootPath . '/' . $file['folder'] . $filename;

	if (!file_exists($Path)) {
		echo json_encode(['status' => 0, 'message' => 'File Not found']);
		exit;
	}

	$newPath = '';
	$saveTo = $RootPath . '/upload_file/' . uniqid('thumb_') . '.jpg';

	$thumbfrom = Input('thumbfrom');

	if ($thumbfrom == 'EXTERNAL_LINK') {
		$thumbURL = trim(Input('thumb_url'));
		if ($thumbURL) {
			urlCopy($thumbURL, $saveTo);
		}
	} else {
		if ($_FILES['thumb']['name']) {
			move_uploaded_file($_FILES['thumb']['tmp_name'], $saveTo);
		}
	}

	if (file_exists($saveTo)) {

		$newPath = $RootPath . '/upload_file/' . uniqid('tag_') . '.jpg';
		try {
			Image::make($saveTo)->resize(400, 400)->save($newPath, THUMB_QUALITY);
			unlink($saveTo);
		} catch (NotReadableException $e) {
			unlink($saveTo);
			echo json_encode(['status' => 0, 'message' => $e->getMessage()]);
			exit;
		}
	}
	$Tagdata = array(
		'Title' => Input('title'),
		'Artist' => Input('artist'),
		'Album' => Input('album'),
		'Year' => Input('year'),
		'Genre' => APP_NAME,
		'Comment' => Input('comment')
	);

	$WriteTag = WriteTag($Path, $newPath, $Tagdata, false);
	if (file_exists($newPath)) {
		unlink($newPath);
	}

	$message = ($WriteTag) ? 'Successfuly Id3Tag Updated' : 'Failed to Write Id3Tag';

	echo json_encode(['status' => 1, 'message' => $message]);
	exit;
} else if ($currentAction == "importfromyoutube") {
	$query = Input('query');
	if (empty($query)) {
		echo json_encode(['status' => 0, 'message' => 'Please Enter Youtube Video URL']);
		exit;
	}
	$request = getApi('http://kpbhost.com/envato/youtube.php', ['video_id' => $query, 'domain' => APP_URL]);
	if ($request) {
		if ($request['status'] == "1") {
			$video = [
				'title' => $request['data']['title'],
				'url' => $request['data']['url'],
				'thumb' => $request['data']['thumb'],
			];
			echo json_encode(['status' => 1, 'message' => $request['message'], 'data' => $video]);
			exit;
		} else {
			echo json_encode(['status' => 0, 'message' => $request['message']]);
			exit;
		}
	} else {
		echo json_encode(['status' => 0, 'message' => 'Server not connect to HOST URL']);
		exit;
	}
}
