<?php

require_once('config.inc.php');

$i=0; $added = array();

$searchValue = (!empty($_GET['search']))    ? $_GET['search']    : '';
$sid         = (!empty($_GET['sid']))       ? $_GET['sid']       : '';
$seasonid    = (!empty($_GET['$seasonid'])) ? $_GET['$seasonid'] : '';

$htmlHead = "<!DOCTYPE html>\n<html>
    <head>
        <title>rommie.servebeer.com</title>
        <link rel='stylesheet' media='screen' href='style.css' type='text/css' />
    </head>
    <body>\n";
$htmlLinks = "        <div>
            <table cellspacing='1' cellpadding='1' border='1'><tbody>
              <tr>
                <td width='50%'><a title='Login to eMule control panel' href='http://rommie.servebeer.com:4711/'>eMule control panel</a></td>
                <td><a title='Login to VNC remote access' href='http://rommie.servebeer.com:5800/'>VNC (Java viewer)</a></td>
              </tr>
              <tr>
                <td><a title='DVDs Database' href='dvds/'>DVDs database</a></td>
                <td><a href='music/'>Music</a></td>
              </tr>
              <tr>
                <td><a href='trac'>trac</a></td>
                <td><a href='svn'>SVN</a></td>
              </tr>
              <tr>
                <td><a href='tools/'>tools</a></td>
                <td><a title='Image Browser' href='browse'>image browser</a></td>
              </tr>
              <tr>
                <td><a href='mail/'>WebMail</a><br /></td>
                <td><a href='phpMyAdmin/'>phpMyAdmin</a></td>
              </tr>
          </tbody></table><br />\n";
$htmlSearch = "        <table border = '1'>
          <tr>
              <td width='50%'>
                  <a href='https://tvunderground.org.ru/index.php'>Search TV Underground</a>
                  <form style='display:inline' method='get' action='" . $_SERVER['PHP_SELF'] . "' target='_top'><input type='text' value='" . htmlspecialchars($searchValue, ENT_QUOTES) . "' name='search' /><input type='hidden' value='search' name='action' /><input type='submit' value='Go' /></form>
              </td>
              <td>
                  <form style='display:inline' method='get' action='" . $_SERVER['PHP_SELF'] . "' target='_top'>Add files to queue: <input type='text' value='" . htmlspecialchars($sid, ENT_QUOTES) . "' name='sid' placeholder='Season ID' /><input type='hidden' value='season' name='action' /><input type='submit' value='Add' /></form>
              </td> 
          </tr>
        </table>
        <br />\n";

$htmlNotice = "";
$htmlBody = "";

// Get existing files
// Files currently downloading...
getFilesFromEmuleDownloading($nonPausedCategories);

//print_r($files); exit;
// All other files queued in emule...
getFilesFromEmuleQueued();
// And all files on the filesystem
//getFilesFromFilesystem($foldersWithEpisodes, '/mnt/media/Episodes/all.txt');
getFilesFromFilesystem($foldersWithEpisodes);

//echo "<pre>" . print_r($files, true) . "</pre>"; exit;

if (!empty($_GET['action'])) {
    $client = new http();
    $client->cookies = $conf['cookies'];
    $results = array();
    $englishDiv = '';

    switch (strtolower($_GET['action'])) {
        case 'search':
            $client->postvars = array('search' => $_GET['search']);
            preg_match_all($regexes['searchResults'], $client->get('https://tvunderground.org.ru/index.php?show=search'), $results);
            $htmlBody .= "<div><hr />Show search results<hr />";
            if (count($results[0]) == 0) { $htmlBody .= "No results :("; }
            for ($i=0;$i<count($results[0]);$i++) {
                $htmlBody .= "<a href='https://tvunderground.org.ru/index.php?show=season&sid={$results['showid'][$i]}' target='_blank'>{$results['title'][$i]}</a> ";
                $htmlBody .= "<form style='display:inline' method='GET' action='" . $_SERVER['PHP_SELF'] . "' target='_top'>
                    <input type='hidden' name='search' value='" . htmlspecialchars($searchValue) . "' />
                    <input type='hidden' name='showid' value='{$results['showid'][$i]}' />
                    <input type='submit' name='action' value='Choose' />
                    </form><br />";
            }
            $htmlBody .= "<hr /></div>";
            //echo "<pre>" . print_r($results, true) . "</pre>";
        break;
        case 'download':
            addNewSeason($_GET['seasonid']);
            $htmlBody .= "Download from season {$_GET['seasonid']}";
            // No break - since I want to show the seasons page again
        case 'choose':
            $pauseall = !empty($_GET['pauseall']) ? true : false;
            $seasonsPage = $client->get('https://tvunderground.org.ru/index.php?show=season&sid=' . $_GET['showid']);
            if (preg_match($regexes['englishDiv'], $seasonsPage, $englishDiv)) {
                preg_match_all($regexes['showSeasons'], $englishDiv[0], $results);
                #echo "<textarea>" . print_r($englishDiv, true) . "</textarea>";
                #echo "<textarea>" . $regexes['showSeasons'] . "</textarea>";
            } else { echo "No englishDiv match"; }
            $htmlBody .= "<div><hr />Season search results<hr />";
            if (count($results[0]) == 0) { $htmlBody .= "No results :("; }
            for ($i=0;$i<count($results[0]);$i++) {
                if (preg_match($regexes['skipSeries'], $results['title'][$i]) && !stristr($results['title'][$i], 'Daily Show')) { continue; }
                $disabled = ($_GET['seasonid'] == $results['seasonid'][$i]) ? " disabled='disabled'" : '';
                $htmlBody .= "<a href='https://tvunderground.org.ru/index.php?show=episodes&sid={$results['seasonid'][$i]}' target='_blank'>{$results['title'][$i]}</a> ";
                $htmlBody .= "<form style='display:inline' method='GET' action='" . $_SERVER['PHP_SELF'] . "' target='_top'>
                    <input type='hidden' name='search' value='" . htmlspecialchars($searchValue) . "' />
                    <input type='hidden' name='showid' value='{$_GET['showid']}' />
                    <input type='hidden' name='seasonid' value='{$results['seasonid'][$i]}' />
                    <input type='submit' name='action' value='Download' {$disabled} />
                    <input type='checkbox' name='pauseall' value='true' " . ($pauseall ? "checked='checked'" : '') . " /> (Pause all?)
                    </form><br />";
            }
            $htmlBody .= "<hr /></div>";
            //echo "<pre>" . print_r($results, true) . "</pre>";
        break;
    }
} else {
    if (!empty($_GET['seasonid'])) {
        addNewSeason($_GET['seasonid']);
    }
    $releases = getNewReleases($feedUrl);

    $htmlBody .= "    <table border = '1'>\n        <tr>\n";

    foreach ($releases as $release) {
        $matches = $fileMatch = array();
        $style   = $endStyle  = '';

        $title = html_entity_decode($release->title);
        if (!preg_match($regexes['titleFromRss'], $title, $matches)) { continue; }
        preg_match('/sid=(?P<sid>[0-9]*)/', $release->link, $linkMatch);
        $latestEp = '';
        // See if this is a show I'm actively tracking...
        $addButton = '';
        //echo "{$matches['series']} - {$release->description}\n\n";
        if (in_array($matches['series'], array_keys($files)) && !in_array($matches['series'], $blacklist)) {
            // Get the release page (using the timestamp of the RSS entry as a cachebuster...
            $style .= "<strong>"; $endStyle .= "</strong>";
            if (!empty($linkMatch['sid'])) {
                $items = getItemsFromSeasonPage($linkMatch['sid'], $release->pubDate);
            }
            // See if there's any files I don't already have...
            foreach ($items as $item => $ed2k) {
                $item = preg_replace($regexes['moveLeadingThe'], '\1, The - ', $item);
                $itemMatch = array();
                if (preg_match($regexes['filename'], $item, $itemMatch)) {
                    // If this is a show I track, and this episode doesn't already exist
//                    echo "{$item}: if (is_array(\$files[{$itemMatch['title']}]) && !in_array({$itemMatch['episode']}, array_keys(\$files[{$itemMatch['title']}]))) {\n";
//                    echo print_r($files[$itemMatch['title']], true) . "\n"; continue;
                    if (
                         isset($files[$itemMatch['title']]) &&
                         is_array($files[$itemMatch['title']]) &&
                         !in_array($itemMatch['episode'], array_keys($files[$itemMatch['title']])) &&
                         !in_array('0' . $itemMatch['episode'], array_keys($files[$itemMatch['title']]))
                       ) {
//                        echo "isset(\$files[\$itemMatch['title']]): " . var_export(isset($files[$itemMatch['title']]), true) . "\n";
//                        echo "is_array(\$files[\$itemMatch['title']]): " . var_export(is_array($files[$itemMatch['title']]), true) . "\n";
//                        echo "!in_array({$itemMatch['episode']}, array_keys(\$files[{$itemMatch['title']}]) " . var_export(!in_array($itemMatch['episode'], array_keys($files[$itemMatch['title']])), true) . "\n";
//                        echo "!in_array('0' . \$itemMatch['episode'], array_keys(\$files[\$itemMatch['title']]))" . var_export(!in_array('0' . $itemMatch['episode'], array_keys($files[$itemMatch['title']])), true) . "\n";
//                        echo "ADD {$item} to  eMule!<br />";
                        if ($addFilesToEmule) { addFileToEmule($item, $ed2k, false, 'tvunderground.org.ru'); }
                    }
                    $latestEp = "<acronym title='" . htmlspecialchars($item, ENT_QUOTES) . "'><a href='{$ed2k}'> [{$itemMatch['episode']}]</a></acronym>";
                } else { $htmlBody .= "Echo no filename match for {$item} - should never happen!"; }
            }
//            echo "<pre>" . print_r($items, true) . "</pre>"; exit;
        } else if (!empty($linkMatch['sid'])) {
            $addButton = "                                 <span style='float: right'><form style='display:inline' method='GET' action='{$_SERVER['PHP_SELF']}' target='_top'>
                                <input type='hidden' name='seasonid' value='{$linkMatch['sid']}' />
                                <input type='submit' name='submit' value='+' />
                                                            </form></span>\n";
        }
        $htmlBody .= "            <td><acronym title='" . htmlspecialchars($release->title, ENT_QUOTES) . " - " . str_replace('&lt;br /&gt;', '', htmlspecialchars($release->description, ENT_QUOTES)) . "'><a href='" . htmlentities($release->link) . "' target='_blank'>{$style}{$matches['series']}{$endStyle}</a></acronym>  {$latestEp} {$addButton}</td>\n";

        if ((++$i % 5) == 0) {
            $htmlBody .= "        </tr>\n        <tr>\n";
        }
    //    print_r($release); exit;
    }
    // Add files from tv4ed2k as well (since tvu seems to be struggling...)
    addFilesFromTv4ed2k();
    $htmlBody .= "    </table>\n    </div>\n</body>\n</html>";
}

if (!empty($added)) {
    $htmlNotice .= "<div class='notice'>";
    foreach ($added as $series => $files) {
        $count = count($files);
        $htmlNotice .= "Added {$count} eps of {$series}<br />";
    }
    $htmlNotice .= "</div><br />";
}

function isAShowIWatch($title) {
    global $files;
}

function isAnEpisodeIDoNotHave($episode, $title) {
    global $files;
    // First - Check if this is a REPACK or PROPER, if so, check if that exact file has been downloaded...

    // Check if I already have this episode number
}


if (PHP_SAPI != 'cli') {
  echo $htmlHead . $htmlNotice . $htmlLinks . $htmlSearch . $htmlBody;
}

?>
