<?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
	)
	*/
chdir(dirname(__FILE__));
	
	$m3uformat = 1;
	include("url.php");
	$db = new SQLite3('iptv.db');
logit ("Starting channels update");

$silent = false;


update($m3uformat);

function logit($msg) {
	global $silent;
	if (!$silent)
		print($msg."\n");
}

function update($format, $silent=false) {
	global $db, $m3url;
	logit(" Loading playlist");
	if($m3u = file_get_contents($m3url)) { 
		
		
		
		$out = "playlist-".date("ymd").".m3u";
		file_put_contents($out,$m3u);
		
		logit(" Playlist loaded");
		$all_lines = file($out);
		$number_of_lines= count($all_lines);
		$percent = (int)($number_of_lines / 100);
		
		logit("  Number of lines to process : $number_of_lines : $percent");
		
		//empty channel list
		$db->exec("DELETE FROM channels");

		logit (" Parsing playlist");
		$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]);
						// Ignore non fr series
						if (!(preg_match('/ SERIES/', $group) && $group != "|FR| SERIES")) {
								//logit ("non fr serie : $group");
								//exit;
						
							$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);
						}
					}
					
				}
				if (($i % $percent) == 0) {
					logit("   $i out of $number_of_lines done.");
				}
				//print($line."\n");
			}
			logit ("Finished processing playlist");
			fclose($handle);
		}
		
	} 
	else {
			logit( " ERROR : error downloading playlist");
	}
}

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));
}

?>