<?php

class PSPRSSSort extends Module
{
    public static $type = Struct::MODULE_TYPE_NORMAL;

    public function run()
    {
        global $gem;

        $gem->css[] = 'psprsssort.css';
        $gem->js[] = 'psprsssort.js';

        $output = '<h1>'.html::escape($gem->struct->cur_page['info'][$gem->i18n->language])."</h1>\n";

        // Save CHLIST
        if (isset($_POST['save'])) {
            $output .= $this->_step3();
        }
        // Sort RSS feeds
        elseif (isset($_FILES['CHLIST'])) {
            $output .= $this->_step2();
        }
        // Upload CHLIST
        else {
            $output .= $this->_step1();
        }

        return [$output, 'Html5', []];
    }

    # Choose file to upload
    private function _step1()
    {
        return <<<HTML
    <form action='{$_SERVER['PHP_SELF']}' method='post' enctype='multipart/form-data' name='form'>
        <h2>Step 1/2</h2>
        <p>
            Upload the file ms0:/PSP/SYSTEM/RSSCH/CHANNELS/CHLIST:
            <br /><br />
            <input type='file' name='CHLIST' /><input type='submit' value='Upload!' />
        </p>
    </form>
HTML;
    }

    # Parse CHLIST and print RSS feed list
    private function _step2()
    {
        if ($_FILES['CHLIST']['name'] != 'CHLIST') {
            message::warning('The file you uploaded is not CHLIST!');
        }
        elseif ($_FILES['CHLIST']['error'] != 0) {
            message::warning("File wasn't uploaded correcty!");
        }
        elseif ($_FILES['CHLIST']['size'] > 50 * 1024) {
            message::warning('File size is too big! Max allowed size is 50kB');
        }

        $fp = fopen($_FILES['CHLIST']['tmp_name'], 'r');
        $rssch = fread($fp, $_FILES['CHLIST']['size']);
        fclose($fp);

        # Parse CHLIST file
        $rssch = substr($rssch, 8);
        $channels = preg_split('/CHAN..../', $rssch);
        $options = '';
        for ($i = 1; $i < count($channels); ++$i) {
            # Max. 6 fields
            for ($j = 0; $j < 5; ++$j) {
                $info = str_replace(' ', '', substr($channels[$i], 0, 4));
                $length = array_pop((unpack('I', substr($channels[$i], 4, 4))));
                $data = substr($channels[$i], 8, $length);
                $channels[$i] = substr($channels[$i], $length + 8);

                $_SESSION["id$i"][$info] = $data;
                if ($channels[$i] == '') {
                    break;
                }
            }
            $options .= "<option value='$i'>".htmlspecialchars($_SESSION["id$i"]['TITL'])."</option>\n";
        }

        # Print multiple select box
        return <<<HTML
    <form action='{$_SERVER['PHP_SELF']}' method='post' enctype='multipart/form-data' name='form'>
        <h2>Step 2/2</h2>
        <p>
            Rearrange the RSS feeds to your liking:
            <br /><br />
            <select name='rssch[]' id='rssch' multiple='multiple'>
                $options
            </select>
            <br /><br />
            <input type='button' onclick='javascript:moveUpList(document.getElementById("rssch")); return false;' value='Up' />
            <input type='button' onclick='javascript:moveDownList(document.getElementById("rssch"))' value='Down' />
            <br /><br />
            <input type='submit' name='save' value='Save!' onclick='selectAll(document.getElementById("rssch"));'/></td>
        </p>
    </form>
HTML;
    }

    # Return file to user
    private function _step3()
    {
        header('Content-Disposition: attachment; filename="CHLIST"');
        echo "CSFF\0\0\0"; # header
        foreach ($_POST['rssch'] as $id) {
            if (!is_numeric($id)) {
                exit;
            }

            $line = '';
            foreach (['URL', 'TITL', 'LINK', 'DESC', 'COPY', 'IMAG'] as $info) {
                if (isset($_SESSION["id$id"][$info])) {
                    $line .= sprintf(
                        '% -4s%s%s',
                        $info,
                        pack('I', mb_strlen($_SESSION["id$id"][$info])),
                        $_SESSION["id$id"][$info]
                    );
                }
            }
            printf('CHAN%s%s', pack('I', mb_strlen($line)), $line);
        }
        exit;
    }
}