<?php

require "/home/hpr/php/include.php";

date_default_timezone_set('UTC');

function goback() {
  header( "Location: " . $_SERVER["HTTP_REFERER"] ) ;
  exit;
}
logextra( "Starting add_show.php");

if ( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
  problem("ERROR: It is not a POST"); 
}
logextra( "It is a POST" );

if ( empty($_SERVER["REMOTE_ADDR"]) ) {
  problem("ERROR: No REMOTE_ADDR");
}
else {
  $ip = $_SERVER["REMOTE_ADDR"];
}
logextra( "We have a IP of $ip" );

if (count($_POST) !== 15) {
  logextra( "POST is not 15" );
  if (count($_POST) !== 17) {
    # 19 is for mosaic
    # if this reports 0 is could be that the max upload is not set correctly in php.ini.
    problem("ERROR: Incorrect number of POST entries ".count($_POST) );
  }
}
logextra( "Correct number of POST entries" );

if ( isset( $_POST['key'] ) and strlen( $_POST['key'] ) ===  45  and strlen( htmlspecialchars( stripslashes( strip_tags( $_POST['key'] ) ) ) ) ===  45 and ctype_xdigit( $_POST['key'] ) ) {
  $db_key = htmlspecialchars( stripslashes( strip_tags( $_POST['key'] ) ) );
}
else {
  problem("ERROR: no key");
}
logextra( "Field lengths are correct" );

$query = "SELECT * FROM reservations WHERE reservations.key = '$db_key' ";
$result = @mysqli_query($connection, $query);
$db = mysqli_fetch_array($result, MYSQLI_ASSOC);
logextra( "Getting this reservation from the db" );

if ( $db["key"] != $db_key ) {
  problem("ERROR: Could not find the reservation in the db");
}
logextra( "Found this reservation from the db" );

if ( empty($_POST["title"]) or strlen($_POST["title"]) > 100 ) {
  problem("ERROR: Title length is not OK");
}
logextra( "Title length is OK" );
$title = $_POST["title"];

if ( empty($_POST["summary"]) or strlen( $_POST["summary"]) > 200 or strlen(str_replace('\\', '', $_POST["summary"])) > 100 ) {
  problem("ERROR: Summary length is not OK");
}
logextra( "Summary length is OK" );
$summary = $_POST["summary"];

if ( empty($_POST["explicit"]) ) {
  problem("ERROR: explicit is missing");
}
logextra( "explicit exists" );

if ( strcmp($_POST["explicit"], "Yes") !== 0 ) {
  logextra( "explicit is not yes" );
  if ( strcmp($_POST["explicit"], "Clean") !== 0 ) {
    problem("ERROR: explicit needs to be either Yes or Clean");
  }
}
logextra( "explicit is either Yes or Clean" );

$explicit = $_POST["explicit"];

if ( $explicit === "Clean" ) {
  $explicit = 0;
}
else {
  $explicit = 1;
}
if ( empty($_POST["episode_license"]) or strlen($_POST["episode_license"]) < 4 or strlen($_POST["episode_license"]) > 11 ) {
  problem("ERROR: episode_license length is not fine");
}
logextra( "episode_license length is fine" );

if ( !(
    strcmp($_POST["episode_license"], "CC-BY-SA") === 0 or 
    strcmp($_POST["episode_license"], "CC-BY-NC-SA") === 0 or 
    strcmp($_POST["episode_license"], "CC-BY-NC-ND") === 0 or 
    strcmp($_POST["episode_license"], "CC-0") === 0 or 
    strcmp($_POST["episode_license"], "CC-BY-NC") === 0 or 
    strcmp($_POST["episode_license"], "CC-BY") === 0 or 
    strcmp($_POST["episode_license"], "Other") === 0 ) 
    ) {
  problem("ERROR: license is not a valid value");  
}
logextra( "license is a valid value" );

$episode_license = $_POST["episode_license"];

if ( empty($_POST["notes"]) or strlen($_POST["notes"]) > 40000 ) {
  problem("ERROR: Notes are missing not less than max");
}
logextra( "Notes are not missing and are less than max" );

$notes = $_POST["notes"];

if ( ( empty($_POST["series"]) and ($_POST["series"] != 0 ) ) or (strlen($_POST["series"]) > 3 ) ) {
  problem("ERROR: Series id is not in the correct range");
}
$series = $_POST["series"];
if ( (strval(intval($series)) != strval($series)) ){
  problem("ERROR: series is not an int");
}
logextra( "series is int" );

$result_series = mysqli_query($connection, "SELECT name FROM miniseries WHERE id='$series'");
logextra( "Series id is in the correct range \"$series\"" );

if (!isset($result_series)) {
  problem("ERROR: Series has not been found");
}
$db_series_name_array = mysqli_fetch_row( $result_series );
$db_series_name = $db_series_name_array[0];

if ( empty($db_series_name) ) {
  problem("ERROR: Series name \"${db_series_name}\" is missing from db ");
}

logextra( "Series name has been found in db: \"$db_series_name\"" );

if ( empty($_POST["series_name"])  ) {
  problem("ERROR: series_name length is not fine");
}
$series_name = $_POST["series_name"];

if ( $series_name != $db_series_name ) {
  problem("ERROR: series_name \"$series_name\" and db_series_name \"$db_series_name\" don't match.");
}

logextra( "series_name checkes passed: \"$series_name\"" );

if ( !empty($_POST["tags"]) and strlen($_POST["tags"]) > 100 ) {
  problem("ERROR: Tags are not the correct length");
}
logextra( "Tags are the correct length" );
$tags = $_POST["tags"];

#############
# Host checks

if ( empty($_POST["host_name"]) or strlen($_POST["host_name"]) > 40 ) {
  problem("ERROR: host_name is not set and not the correct length");
}
logextra( "host_name is set and correct length" );
$host_name = $_POST["host_name"];


if ( strlen($_POST["host_profile"]) > 2000 ) {
  problem("ERROR: host_profile is not the correct length");
}
logextra( "host_profile is correct length" );

$host_profile = $_POST["host_profile"];

if ( empty($_POST["host_license"]) or strlen($_POST["host_license"]) < 4 or strlen($_POST["host_license"]) > 11 ) {
  problem("ERROR: host_license is not in the correct range");
}
logextra( "host_license is in the correct range" );

if ( !(
    strcmp($_POST["host_license"], "CC-BY-SA") === 0 or 
    strcmp($_POST["host_license"], "CC-BY-NC-SA") === 0 or 
    strcmp($_POST["host_license"], "CC-BY-NC-ND") === 0 or 
    strcmp($_POST["host_license"], "CC-0") === 0 or 
    strcmp($_POST["host_license"], "CC-BY-NC") === 0 or 
    strcmp($_POST["host_license"], "CC-BY") === 0 or 
    strcmp($_POST["host_license"], "Other") === 0 ) 
    ) {
  problem("ERROR: host_license is not a predfined value");  
}
logextra( "host_license is a predfined value" );

$host_license = $_POST["host_license"];

if ( $_POST["hostid"] == 0 ) {
  problem("ERROR: hostid is 0");
}
logextra( "hostid is not 0" );

if ( empty($_POST["hostid"])  ) {
  problem("ERROR: hostid doesn't exists ");
}
logextra( "hostid exists " );

$result = mysqli_query($connection, 'SELECT MAX(hostid) FROM hosts;');
if (!isset($result)) {
  problem("ERROR: could not get the max host from db");
}
$maxhost_array = mysqli_fetch_row( $result );
$maxhost = $maxhost_array[0];
logextra( "retrieved the max host from db" );

$hostid = $_POST["hostid"];
if ( (strval(intval($hostid)) != strval($hostid)) ){
  problem("ERROR: host id is not an int");
}
logextra( "host id is int" );

if ( ( intval($hostid) < 0 ) or ( intval($hostid) > $maxhost ) ){
  problem("ERROR: host id \"$hostid\" is not in the correct range \" $maxhost \"");
}
logextra( "host id is int, and in the correct range" );

$query = "SELECT * FROM `hosts` WHERE `hostid` = '$hostid' and `host` = '$host_name';";
$result = @mysqli_query($connection, $query);
$db = mysqli_fetch_array($result, MYSQLI_ASSOC);

logextra( "Getting this host from the db" );

if ( ( $db["hostid"] != $hostid ) or ( $db["host"] != $host_name ) ) {
  problem("ERROR: Could not find the host \"" . $db["hostid"] ."\",  \"" .  $db["host"] . "\" in the db \"${hostid}\", \"${host_name}\"" . $query );
}
logextra( "Found this reservation from the db" );

if ( ( $db["profile"] != "$host_profile" ) or ( $db["license"] != "$host_license" ) ) {
  logextra("The host_license is different to that in the db");
  $query = "UPDATE `hosts` SET `profile` = '$host_profile', `license` = '$host_license'  WHERE `hosts`.`hostid` = '$hostid';";
  $result = mysqli_query($connection, $query );
  if (!isset($result)) {
    problem("ERROR: could not update the host profile");
  } else {
    logextra( "Updating the host profile" );
  }
}
logextra( "The host_license is the same to that in the db" );

##############
# Episode Check
// SHOW_SUBMITTED → METADATA_PROCESSED → SHOW_POSTED → MEDIA_TRANSCODED → UPLOADED_TO_IA → UPLOADED_TO_RSYNC_NET


if ( !empty($_POST["ep_num"]) and isset( $_POST["ep_num"] ) ) {
    $ep_num = intval( $_POST["ep_num"] );
}
else {
    problem("ERROR: ep_num is empty");
}

// // SELECT MAX(ep_num) FROM `reservations` → 3627
// // SELECT MIN(ep_num) FROM `reservations` WHERE ep_num > 0 → 3582
// 
$result = mysqli_query($connection, 'SELECT MAX(ep_num) FROM `reservations`;');
if (!isset($result)) {
    problem("ERROR: Can't get max eps from reservations");
}
$max_eps_array = mysqli_fetch_row( $result );
$max_eps = $max_eps_array[0];
mysqli_free_result($result);

$result = mysqli_query($connection, 'SELECT MIN(ep_num) FROM `reservations` WHERE ep_num > 0;');
if (!isset($result)) {
    problem("ERROR: Can't get min eps from reservations");
}
$min_eps_array = mysqli_fetch_row( $result );
$min_eps = $min_eps_array[0];
mysqli_free_result($result);

if ( empty( $ep_num )  ) {
    problem("ERROR: ep_num is empty");
}

if ( $ep_num < $min_eps ) {
    problem("ERROR: ep_num is too small");
}

if ( $ep_num > $max_eps ) {
    problem("ERROR: ep_num is too big");
}

if ( intval($ep_num) === 0 ) {
  problem("ERROR: ep_num is 0");
}
else {
  $ep_num = intval($ep_num);
}

$result = mysqli_query($connection, "SELECT ep_num FROM reservations WHERE ep_num='$ep_num' AND status='METADATA_PROCESSED';");
if (!isset($result)) {
    problem("ERROR: Cant get info from reservations db");
}
$db_ep_num_array = mysqli_fetch_row( $result );
$db_ep_num = $db_ep_num_array[0];
mysqli_free_result($result);

if ( $db_ep_num != $ep_num ){
    problem("ERROR: Cant find $ep_num with status of METADATA_PROCESSED");
}

$result = mysqli_query($connection, "SELECT `id` FROM `eps` WHERE `id` = '$ep_num';");
if (!isset($result)) {
    problem("ERROR: The show $ep_num is already in the eps db");
}
$db_ep_num_array = mysqli_fetch_row( $result );
$db_ep_num = $db_ep_num_array[0];
mysqli_free_result($result);
if ( !empty( $db_ep_num )  ) {
    problem("ERROR: $ep_num is already in the eps table");
}
if ( intval($db_ep_num) === $ep_num ) {
  problem("ERROR: $ep_num is already in the eps table");
}
logextra( "ep_num checkes passed: $ep_num" );


if ( !preg_match("/^\d{4}-\d{2}-\d{2}$/", $_POST["ep_date"]) ) {
  problem("ERROR: ep_date fails the regex match ");
}
else {
  $ep_date = $_POST["ep_date"];
}

if ( strtotime($ep_date) === false ) {
  problem("ERROR: ep_date didn't convert to date");
}
else {
  $ep_date_epoch = strtotime($ep_date);
}
logextra( "ep_date checkes passed: $ep_date" );


if ( !empty($_POST["duration"]) and isset( $_POST["duration"] ) ) {
  $duration = intval( $_POST["duration"] );
}
else {
    problem("ERROR: duration is empty");
}

if ( empty( $duration )  ) {
    problem("ERROR: duration is empty");
}

if ( $duration < 50 ) {
    problem("ERROR: duration is too small");
}

if ( $duration > 26830 ) {
    problem("ERROR: duration is too big");
}

if ( intval($duration) === 0 ) {
  problem("ERROR: duration is 0");
}
else {
  $duration = intval($duration);
}
logextra( "duration checkes passed: $duration" );

$title = mysqli_real_escape_string( $connection, $title );
$summary = mysqli_real_escape_string( $connection, $summary );
$notes = mysqli_real_escape_string( $connection, $notes );
$tags = mysqli_real_escape_string( $connection, $tags );

$query_add = "INSERT INTO eps VALUES ('$ep_num', '{$ep_date}', '{$title}', '{$duration}', '{$summary}', '{$notes}', '{$hostid}', '{$series}', '{$explicit}', '{$episode_license}', '{$tags}', '0', '0', '0')";

$result = mysqli_query($connection, $query_add );
if(!$result) {
  problem("ERROR: DB problem - The show $ep_num was not added to the eps db.");
}
if (mysqli_errno( $connection )) {
  $error = "MySQL error ".mysqli_errno( $connection ).": ".mysqli_error()."\n";
  problem("ERROR: MySQL error- The show $ep_num was not added to the eps db.\n$error");
} 

$result = mysqli_query($connection, "SELECT `id` FROM `eps` WHERE `id` = '$ep_num';");
if (!isset($result)) {
  problem("ERROR: DB problem - The show $ep_num has not been added to the eps db");
}
$db_ep_num_array = mysqli_fetch_row( $result );
$db_ep_num = $db_ep_num_array[0];
mysqli_free_result($result);
if (mysqli_errno( $connection )) {
  $error = "MySQL error ".mysqli_errno( $connection ).": ".mysqli_error()."\n";
  problem("ERROR: MySQL error- The show $ep_num was not added to the eps db.\n$error");
}

$result = mysqli_query($connection, "UPDATE reservations SET `status` = 'SHOW_POSTED' WHERE `ep_num` = '$ep_num' AND status='METADATA_PROCESSED';" );
if (!isset($result)) {
  problem("ERROR: DB problem - The show $ep_num has not been added to the eps db");
}
if (mysqli_errno( $connection )) {
  $error = "MySQL error ".mysqli_errno( $connection ).": ".mysqli_error()."\n";
  problem("ERROR: Could not update the show reservation to SHOW_POSTED in the db");
}

logextra( "Finished $ep_num ." );
?>
