<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include_once 'config.php';
include_once 'yt.php';
include_once 'db.php';
include_once 'wp.php';
		header("content-type:text/html;charset=utf-8");
kanallar_kontrol();
videolar_kontrol();

function videolar_kontrol()
{
	global $database;
	$videolar = $database->query("SELECT * FROM `videos` WHERE status=0 ");
	if ($videolar->num_rows > 0) {
		while ($row = $videolar->fetch_assoc()) {
			$video_sonuc = video_post_ekle($row['url'], get_channel($row['last'])['category']);
		
			if($video_sonuc>0){
				$database->query("UPDATE `videos` SET `status`=1 WHERE id='" . $row['id'] . "'");
				$database->query("UPDATE `channels` SET `last`=" . $row['id'] . " WHERE id='" . $row['last'] . "'");
			}
		}
	}
}
function kanallar_kontrol()
{
	global $database, $last_num;
	$kanallar = $database->query("SELECT * FROM `channels` WHERE status='1' ");
	if ($kanallar->num_rows > 0) {
		while ($row_kanal = $kanallar->fetch_assoc()) {
			$videolar = kanal_videolar($row_kanal['url']);
			$videolar = array_reverse($videolar);
			$last_video_url = '';
			$last_video_result = $database->query("SELECT * FROM `videos` WHERE id='" . $row_kanal['last'] . "'");
			if ($last_video_result->num_rows > 0) {
				while ($row_video = $last_video_result->fetch_assoc()) {
					$last_video_url = $row_video['url'];
				}
			}
			if (count($videolar) > 0) {
				if (in_array($last_video_url, $videolar)) {
					$gecildi = false;
					foreach ($videolar as $video) {
						if ($video == $last_video_url) {
							$gecildi = true;
						} else if ($gecildi) {
							add_if_url_not_contain('videos', $video, "INSERT INTO `videos`(`url`,`status`,`last`) VALUES ('$video',0,'" . $row_kanal['id'] . "')");
						}
					}
				} else {
					if (count($videolar) >= $last_num) {
						for ($i = count($videolar) - $last_num; $i < count($videolar); $i++) {
							$vid_url = $videolar[$i];
							add_if_url_not_contain('videos', $videolar[$i], "INSERT INTO `videos`(`url`,`status`,`last`) VALUES ('$vid_url',0,'" . $row_kanal['id'] . "')");
						}
					} else {
						foreach ($videolar as $video) {
							add_if_url_not_contain('videos', $video, "INSERT INTO `videos`(`url`,`status`,`last`) VALUES ('" . $video . "',0,'" . $row_kanal['id'] . "')");
						}
					}
				}
			}
		}
	}
}
