<?php
/* DATABASE
CREATE TABLE IF NOT EXISTS channels (
	'name' TEXT NOT NULL,
	'group' TEXT NOT NULL,
	'logo' TEXT NOT NULL,
	'url' TEXT NOT NULL
	);
	
CREATE TABLE groups (
	'idg' INTEGER PRIMARY KEY AUTOINCREMENT,
	'order' INTEGER NOT NULL,
	'name' TEXT NOT NULL
	);
	
CREATE TABLE selchannels (
	'idc' INTEGER PRIMARY KEY AUTOINCREMENT,
	'order' INTEGER NOT NULL,
	'name' TEXT NOT NULL,
	'idg' INTERGER NOT NULL
	);
	
CREATE TABLE rawgroups (
	'name' TEXT NOT NULL
	)
	*/
	
	$section = isset($_REQUEST['s'])?strtoupper($_REQUEST['s']):null;
	$m3uformat = 1;
	include("url.php");
	$db = new SQLite3('iptv.db');
   
	

switch($section) {
	case "SUPDATE":
		update($m3uformat,true);
		break;
	case "DOWNLOAD":
		update($m3uformat);
		break;
	
	case "GROUPS":
		listGroups();
		break;
		
	case "CHANNELS":
		if (!isset($_REQUEST['g'])) {
			print("ERR:nogroup");
		}
		else {
			$group = $_REQUEST['g'];
			$req = "SELECT * FROM channels WHERE `group` LIKE '$group' ORDER BY `name`";
			$chans = array();
			$ret = $db->query($req);
			while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {
				$chans[] = $row;
			}
			$raw = false;
			if ($res = $db->querySingle("SELECT `name` FROM `rawgroups` WHERE `name` LIKE '$group';"))
				$raw = true;
			$result = array( "raw" => $raw, "chans" => $chans);
			print(json_encode($result));
		}
		break;
	case "SETRAW":
		if (!isset($_REQUEST['g'])) {
			print("ERR:nogroup");
		}
		else if (!isset($_REQUEST['v'])) {
			print("ERR:rawnov");
		}
		else {
			$group = $_REQUEST['g'];
			if ((int)$_REQUEST['v'])
				$db->exec("INSERT INTO `rawgroups`(`name`) VALUES('$group');");
			else
				$db->exec("DELETE FROM `rawgroups` WHERE `name` LIKE '$group';");
		}
		break;
	
	case "NEWCGRP":
		if (!isset($_REQUEST['cgroup'])) {
			print("ERR:nocgroup");
		}
		else {
			
			$cgroup = $_REQUEST['cgroup'];
			$req = "SELECT MAX(`order`) FROM `groups`";
			$order = 0;
			if ($ret = $db->querySingle($req)) {
				$order = $ret;
			}
			$order++;
			$req = "INSERT INTO `groups`(`order`,`name`) VALUES($order,'$cgroup')";
			$db->exec($req);
			listCGroups();
		}
		break;
	case "CGROUPS":
		listCGroups();
		break;
	case "DNG":
		if (!isset($_REQUEST['id'])) {
			print("ERR:dngnoid");
		}
		else {
			$id = $_REQUEST['id'];
			$order=$db->querySingle("SELECT `order` FROM `groups` WHERE idg=$id");
			$ordern= $order + 1;
			if ($db->querySingle("SELECT idg FROM `groups` WHERE `order`=$ordern")) {
				$db->exec("UPDATE `groups` SET `order`=$order WHERE `order`=$ordern");
				$db->exec("UPDATE `groups` SET `order`=$ordern WHERE `idg`=$id");
			}
			listCGroups();
		}
		break;
	case "UPG":
		if (!isset($_REQUEST['id'])) {
			print("ERR:upgnoid");
		}
		else {
			$id = $_REQUEST['id'];
			$order=$db->querySingle("SELECT `order` FROM `groups` WHERE idg=$id");
			$ordern= $order - 1;
			if ($db->querySingle("SELECT idg FROM `groups` WHERE `order`=$ordern")) {
				$db->exec("UPDATE `groups` SET `order`=$order WHERE `order`=$ordern");
				$db->exec("UPDATE `groups` SET `order`=$ordern WHERE `idg`=$id");
			}
			listCGroups();
		}
		break;
	
	case "RMG":
		if (!isset($_REQUEST['id'])) {
			print("ERR:rmgnoid");
		}
		else {
			$id = $_REQUEST['id'];
			if ($order=$db->querySingle("SELECT `order` FROM `groups` WHERE idg=$id")) {
			
				$db->exec("UPDATE `groups` SET `order`=`order` - 1 WHERE `order`>$order");
				$db->exec("DELETE FROM selchannels WHERE `idg`=$id");
				$db->exec("DELETE FROM `groups` WHERE `idg`=$id");
			}
			listCGroups();
		}
		break;	
	case "RNG":
		if (!isset($_REQUEST['id'])) {
			print("ERR:rngnoid");
		}
		else if (!isset($_REQUEST['n'])) {
			print("ERR:rngnoname");
		}
		else {
			$id = $_REQUEST['id'];
			$name = $_REQUEST['n'];
			
			$db->exec("UPDATE `groups` SET `name`='$name' WHERE `idg`=$id");
			listCGroups();
		}
		break;	
	case "RAWLST":
		$ret = $db->query("SELECT `name` FROM `rawgroups`");
		while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {
			print( $row['name']."\n");
		}
		break;
	case "DNC":
		if (!isset($_REQUEST['id'])) {
			print("ERR:dncnoid");
		}
		else {
			$id = $_REQUEST['id'];
			$order=$db->querySingle("SELECT `order` FROM `selchannels` WHERE idc=$id");
			$idg=$db->querySingle("SELECT `idg` FROM `selchannels` WHERE idc=$id");
			$ordern= $order + 1;
			if ($db->querySingle("SELECT idc FROM `selchannels` WHERE `order`=$ordern")) {
				$db->exec("UPDATE `selchannels` SET `order`=$order WHERE `order`=$ordern AND `idg`=$idg" );
				$db->exec("UPDATE `selchannels` SET `order`=$ordern WHERE `idc`=$id");
			}
			listSChans($idg);
		}
		break;
	case "UPC":
		if (!isset($_REQUEST['id'])) {
			print("ERR:upcnoid");
		}
		else {
			$id = $_REQUEST['id'];
			$order=$db->querySingle("SELECT `order` FROM `selchannels` WHERE idc=$id");
			$idg=$db->querySingle("SELECT `idg` FROM `selchannels` WHERE idc=$id");
			$ordern= $order - 1;
			if ($db->querySingle("SELECT idc FROM `selchannels` WHERE `order`=$ordern")) {
				$db->exec("UPDATE `selchannels` SET `order`=$order WHERE `order`=$ordern AND `idg`=$idg" );
				$db->exec("UPDATE `selchannels` SET `order`=$ordern WHERE `idc`=$id");
			}
			listSChans($idg);
		}
		break;
	
	case "RMC":
		if (!isset($_REQUEST['id'])) {
			print("ERR:rmcnoid");
		}
		else {
			$id = $_REQUEST['id'];
			if ($order=$db->querySingle("SELECT `order` FROM `selchannels` WHERE idc=$id")) {
				$idg=$db->querySingle("SELECT `idg` FROM `selchannels` WHERE idc=$id");
				
				$db->exec("UPDATE `selchannels` SET `order`=`order` - 1 WHERE `idg`=$idg AND `order`>$order");
				$db->exec("DELETE FROM selchannels WHERE `idc`=$id");
				listSChans($idg);
			}
			
		}
		break;	
		
	case "SCHANS":
		if (!isset($_REQUEST['id'])) {
			print("ERR:schannoid");
		}
		else {
			listSChans($_REQUEST['id']);
		}
		break;
	case "ADDSCHAN":
		if (!isset($_REQUEST['idg'])) {
			print("ERR:addscnoidg");
		}
		else if (!isset($_REQUEST['name'])) {
			print("ERR:addsconame");
		}
		else {
			$idg = $_REQUEST['idg'];
			$name = $_REQUEST['name'];
			$req = "SELECT MAX(`order`) FROM `selchannels` WHERE `idg`=$idg";
			$order = 0;
			if ($ret = $db->querySingle($req)) {
				$order = $ret;
			}
			$order++;
			$req = "INSERT INTO `selchannels`(`order`,`name`, `idg`) VALUES($order,'$name', $idg)";
			$db->exec($req);
			listSChans($idg);
		}
		break;
	default:
		print("ERR:s");
		break;
}

function update($format, $silent=false) {
	global $db, $m3url;
	print "b";
	if($m3u = file_get_contents($m3url)) { 
		$out = "playlist-".date("ymd").".m3u";
		file_put_contents($out,$m3u);
		//empty channel list
		$db->exec("DELETE FROM channels");


		$handle = fopen($out, "r");
		if ($handle) {
			$i = 0;
			while (($line = fgets($handle)) !== false) {
				$i++;
				if ($format == 1) {
					if (preg_match('/^#EXTINF:0 group-title="([^"]+)"tvg-logo="([^"]+)",(.*)$/',$line,$matches)) {
						$i++;
						$url = trim(fgets($handle));
						$req = "INSERT INTO 'channels'('name','group','logo','url') VALUES('$matches[3]', '$matches[1]', '$matches[2]', '$url')";
						$db->exec($req);
					}
				}
				else if ($format == 2) {
					//print "OK\n";
					if (preg_match('/^#EXTINF:-1 tvg-id="[^"]*" tvg-name="[^"]+" tvg-logo="([^"]+)" group-title="([^"]+)",\|.*\| (.*)$/i',$line,$matches)) {
						$name = str_replace("'","''",$matches[3]);
						$group = str_replace("'","''",$matches[2]);
						$logo = $matches[1];
						$i++;
						$url = trim(fgets($handle));

						$count = $db->querySingle("SELECT COUNT(`name`) FROM `channels` WHERE `name` = '$name' OR `name` LIKE '$name/%'");
						if ($count) {
							//print ($count).$name."\n";
							$name .= "/".$count;
						}
						//print "\n\n--$line--\nn+$name\ng+$group\nu+$url\n";
						$req = "INSERT INTO 'channels'('name','group','logo','url') VALUES('$name', '$group', '$logo', '$url')";
						$db->exec($req);
					}
					
				}
				//print($line."\n");
			}

			fclose($handle);
		}		 
		
		if (!$silent)
			listGroups();
	} 
	else
		if (!$silent)
			print "ERR:dl";
}

function listGroups() {
	global $db;
	$groups = array();
	$req = "SELECT `group` FROM `channels` GROUP BY `group`;";
	$ret = $db->query($req);
	while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {
		$groups[] = $row['group'];
	}
	
	print(json_encode($groups));
}

function listCGroups() {
	global $db;
			$req = "SELECT * FROM `groups` ORDER BY `order`";
			$groups = array();
			$ret = $db->query($req);
			while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {
				$groups[] = $row;
			}
			print(json_encode($groups));	
}

function listSChans($idg) {
	global $db;
	$chans = array();
	$req = "SELECT `idc`,`selchannels`.`name` AS name,`channels`.`logo` AS logo,`channels`.`url` AS url	FROM selchannels INNER JOIN `groups` on `groups`.`idg`=`selchannels`.`idg` INNER JOIN `channels` ON `selchannels`.`name`==`channels`.`name` 
		WHERE `selchannels`.`idg`=$idg ORDER BY `selchannels`.`order`;"; 
	$ret = $db->query($req);
	while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {
		$chans[] = $row;
	}
	print(json_encode($chans));
}

?>