<?php
/**
 * -------------------------------------------------------------------------
 *
 * The snippet for rendering the News edit form.
 *
 * -------------------------------------------------------------------------
 *
 * These system variables are available:
 *
 *     $params   = FALSE or the current publication          ( see file    tiny.news.feed/Themes/default/news-add.tpl
 *                                                             or see file tiny.news.feed/Themes/default/news-edit.tpl )
 *     $cms      = your application                          ( see file mimimi.core/Routines.php -> mimimiInclude -> $cms )
 *     $folder   = relative path of the application's folder ( see file mimimi.core/Routines.php -> mimimiInclude -> $folder )
 *     $filename = relative path of this TPL file            ( see file mimimi.core/Routines.php -> mimimiInclude -> $filename )
 *     $file     = absolute path of this TPL file            ( see file mimimi.core/Routines.php -> mimimiInclude -> $file )
 *
 * -------------------------------------------------------------------------
 *
 * @package    MimimiFramework
 * @subpackage Examples / Tiny News Feed site
 * @license    GPL-2.0
 *             https://opensource.org/license/gpl-2-0/
 * @copyright  2022 MiMiMi Community
 *             https://mimimi.software/
 *
 * -------------------------------------------------------------------------
 */

/**
 * -------------------------------------------------------------------------
 *
 * Take the steps that match the functionality of this form.
 *
 * -------------------------------------------------------------------------
 */

                                                        // -----------------
    $ok = $cms->amIAdmin();                             // am I admin? ( see file tiny.news.feed/Application.php -> amIAdmin )
                                                        // -----------------
    if ( $ok ) {                                        // if it's true
        $id = printItemField('id', $params, FALSE);     //     get the publication ID ( see file mimimi.modules/Helper/Helper.php -> printItemField )
                                                        // -----------------
        $error   = '';                                  //     no error now
        $success = '';                                  //     no success now
        $item    = [ ];                                 //     no record now
        $ok = getFormInput('submit');                   //     get a form posting marker ( see file mimimi.modules/Helper/Helper.php -> getFormInput )
                                                        // -----------------
        if ( $ok ) {                                    //     if that form is posted by human's click
            $error = TINYFEED_ERROR_ID_SPOOFING;        //         let's say there is an error        ( see file tiny.news.feed/Constants.php -> TINYFEED_ERROR_ID_SPOOFING )
            $ok = $id == getFormInput('id');            //         check for attack based on ID field ( see mimimi.modules/Helper/Helper.php -> getFormInput )
                                                        // -----------------
            if ( $ok ) {                                //         if no attack
                $url = getFormInput('url');             //             get a page URL ( see file mimimi.modules/Helper/Helper.php -> getFormInput )
                if ( $url == '' ) {                     //             if URL is not specidied
                    $url = mimimiRandomId(              //                 generate random URL ( see file mimimi.core/Routines.php -> mimimiRandomId )
                               40                       //                 . . of this length
                           );                           //
                }                                       //
                $long = 'news/' . $url;                 //             build a long relative URL
                                                        // -----------------
                $file = mimimiFiles('upload');          //             get uploaded file ( see file mimimi.core/Routines.php -> mimimiFiles )
                $from = ! empty($file['tmp_name'])      //             get the temporary file URL
                            ? $file['tmp_name']         //             . . on successful uploading
                            : '';                       //             . . when there is no uploading
                $file = ! empty($file['size']) &&       //             get the file URL
                        $file['error'] == UPLOAD_ERR_OK //             . .
                            ? basename($file['name'])   //             . . on successful uploading
                            : '';                       //             . . when there is no uploading
                                                        // -----------------
                $image = getFormInput('image');         //             get a page photo URL ( see file mimimi.modules/Helper/Helper.php -> getFormInput )
                if ( $image == '' ) {                   //             if it is not specified
                    if ( $file ) {                      //                 if the file is uploaded
                        $image = 'media/' . $long . '/' . $file; //            build the matching URL
                    }                                   //
                }                                       //
                                                        // -----------------
                $error = TINYFEED_ERROR_BAD_IMAGE;      //             let's say there is an error ( see file tiny.news.feed/Constants.php -> TINYFEED_ERROR_BAD_IMAGE )
                $valid =  [ 'webp',                     //             make a list of valid image file extensions
                            'jpg',                      //
                            'jpeg',                     //
                            'png',                      //
                            'gif',                      //
                            'bmp',                      //
                            'svg' ];                    //
                $ok = $image == ''                      //             validate the image URL
                      || validateMedia($image, $valid); //
                                                        // -----------------
                if ( $ok ) {                            //             if that image URL is valid
                    $error = TINYFEED_ERROR_EMPTY_NEWS; //                 let's say there is an error ( see file tiny.news.feed/Constants.php -> TINYFEED_ERROR_EMPTY_NEWS )
                    $item = [                           //                 get the form's fields
                        'enabled' => getFormInput('enabled') //            . . page visibility ( see file mimimi.modules/Helper/Helper.php -> getFormInput )
                                                 == TRUE, //
                        'title'   => getFormInput('title'), //             . . page name       ( see file mimimi.modules/Helper/Helper.php -> getFormInput )
                        'meta'    => getFormInput('meta'), //              . . page short text ( see file mimimi.modules/Helper/Helper.php -> getFormInput )
                        'image'   => $image,            //                 . . page photo
                        'body'    => tinySanitize(      //                 . . page full text  ( see file tiny.news.feed/Helper/Helper.php -> tinySanitize )
                                         getFormInput('body') //               . . ( see file mimimi.modules/Helper/Helper.php -> getFormInput )
                                     ),                 //
                        'url'     => $url               //                 . . page URL
                    ];                                  //
                                                        // -----------------
                    if ( $item['title'] || $item['meta']//                 if something has been entered
                    ||   $item['body']  || $image ) {   //
                                                        // -----------------
                        $error = TINYFEED_ERROR_URL_CONFLICT; //               let's say there is an error   ( see file tiny.news.feed/Constants.php -> TINYFEED_ERROR_URL_CONFLICT )
                        $ok = $cms                      //                     check for a conflict with URL
                              ->viewers                 //                     . . via VIEWERS module ( see file tiny.news.feed/Viewers/Viewers.php )
                              ->news                    //                     . . via NEWS submodule ( see file tiny.news.feed/Viewers/News/News.php -> testBy )
                              ->testBy(                 //                     . . using this method
                                  'url',                //                         . . by this column
                                  $url,                 //                         . . with this value
                                  $id                   //                         . . except for the publication with this identifier
                              );                        //
                                                        // -----------------
                        if ( $ok ) {                    //                     if there are no URL doubles
                            $error   = '';              //                         no error now
                            $success = TINYFEED_ERROR_DEMO; //                     let's say there is a success ( see file tiny.news.feed/Constants.php -> TINYFEED_ERROR_DEMO )
                                                        // -----------------
                            if ( ! TINYFEED_ON_DEMO_NOW ) { //                     if we are not in demo mode ( see file tiny.news.feed/Constants.php -> TINYFEED_ON_DEMO_NOW )
                                $id ? $cms              //                             update this news in the database
                                      ->viewers         //                             . . via VIEWERS module ( see file tiny.news.feed/Viewers/Viewers.php )
                                      ->news            //                             . . via NEWS submodule ( see file tiny.news.feed/Viewers/News/News.php -> mimimi.core/ModuleWithTable.php -> update )
                                      ->update($id, $item) //                              . . using this method
                                    : $cms              //                             or add this news to the database
                                      ->viewers         //                             . . via VIEWERS module ( see file tiny.news.feed/Viewers/Viewers.php )
                                      ->news            //                             . . via NEWS submodule ( see file tiny.news.feed/Viewers/News/News.php -> mimimi.core/ModuleWithTable.php -> add )
                                      ->add($item);     //                             . . using this method
                                                        // -----------------
                                $old = printItemField(  //                             get the publication image URL ( see file mimimi.modules/Helper/Helper.php -> printItemField )
                                           'image',     //                             . . from this column
                                           $params,     //                             . . from this publication
                                           FALSE        //                             . . return as result, do not print
                                       );               //
                                                        // -----------------
                                if ( $old ) {           //                             if this publication contains old image
                                    if ( $old != $image) { //                              if new image is another
                                        $ok = $cms      //                                     check for a conflict with URL of old image
                                              ->viewers //                                     . . via VIEWERS module ( see file tiny.news.feed/Viewers/Viewers.php )
                                              ->news    //                                     . . via NEWS submodule ( see file tiny.news.feed/Viewers/News/News.php -> testBy )
                                              ->testBy( //                                     . . using this method
                                                  'image', //                                      . . . . by this column
                                                  $old, //                                     . . . . with this value
                                                  $id   //                                     . . . . except for the publication with this identifier
                                              );        //
                                                        // -----------------
                                        if ( $ok ) {    //                                     if there are no URL doubles
                                            removeMedia($old); //                                      remove old image ( see file mimimi.modules/Helper/Helper.php -> removeMedia )
                                        }               //
                                    }                   //
                                }                       //
                                                        // -----------------
                                if ( $file ) {          //                             if there is an uploaded file
                                    uploadMedia(        //                                 move that file to the media folder
                                        $image,         //                                 . . to this location
                                        $from,          //                                 . . from this temporary location
                                        $valid          //                                 . . only if it matches these extensions
                                    );                  //
                                }                       //
                                                        // -----------------
                                $site = printSiteUrl(FALSE); //                        get your site URL ( see file mimimi.modules/Helper/Helper.php -> printSiteUrl )
                                mimimiStop(             //                             stop execution    ( see file mimimi.core/Routines.php -> mimimiStop )
                                    $site . $long,      //                             . . and go to that news page
                                    307                 //                             . . using 307 redirect
                                );                      //
                            }                           //
                        }                               //
                    }                                   //
                                                        // -----------------
                    $params = $item;                    //                 use fields entered
                }                                       //
            }                                           //
        }                                               //
                                                        // -----------------

        /**
         * -----------------------------------------------------------------
         *
         * HTML markup of that form.
         *
         * -----------------------------------------------------------------
         */
         ?>

            <input name="id" type="hidden" value="<?php printValue($id) ?>">

            <div class="error"  ><?php printValue($error)   ?></div>
            <div class="success"><?php printValue($success) ?></div>

            <fieldset>
                <label>
                    <small>
                        <?php printValue(TINYFEED_INTERFACE_URL_LABEL) ?>
                        <small>
                            <?php printSiteUrl() ?>news/
                        </small>
                    </small>
                    <input name="url"
                           type="text"
                           onblur="correctPageUrl()"
                           value="<?php printItemField('url', $params) ?>"
                           maxlength="250">
                    <span>
                        <?php printValue(TINYFEED_INTERFACE_URL_REMARK) ?>
                    </span>
                </label>
            </fieldset>

            <fieldset class="switch">
                <label>
                    <input name="enabled" value="1" type="checkbox" <?php echo printItemField('enabled', $params, FALSE)
                                                                               ? 'checked'
                                                                               : '' ?>>
                    <?php printValue(TINYFEED_INTERFACE_ENABLED_LABEL) ?>
                </label>
            </fieldset>

            <fieldset>
                <label>
                    <small>
                        <?php printValue(TINYFEED_INTERFACE_TITLE_LABEL) ?>
                    </small>
                    <input name="title" type="text" value="<?php printItemField('title', $params) ?>" maxlength="100">
                    <span>
                        <?php printValue(TINYFEED_INTERFACE_TITLE_REMARK) ?>
                    </span>
                </label>

                <label>
                    <small>
                        <?php printValue(TINYFEED_INTERFACE_META_LABEL) ?>
                    </small>
                    <textarea name="meta" rows="4" maxlength="300"><?php printItemField('meta', $params) ?></textarea>
                    <span>
                        <?php printValue(TINYFEED_INTERFACE_META_REMARK) ?>
                    </span>
                </label>

                <label>
                    <small>
                        <?php printValue(TINYFEED_INTERFACE_BODY_LABEL) ?>
                    </small>
                    <textarea name="body" rows="8" maxlength="6000"><?php printItemField('body', $params) ?></textarea>
                    <span>
                        <?php printValue(TINYFEED_INTERFACE_BODY_REMARK) ?>
                    </span>
                </label>
            </fieldset>

            <fieldset>
                <label>
                    <small>
                        <?php printValue(TINYFEED_INTERFACE_IMGFILE_LABEL) ?>
                    </small>
                    <!-- maximal file size is 5Mb, that is 5 * 1024 * 1024 = 5242880 bytes -->
                    <input type="hidden" name="MAX_FILE_SIZE" value="5242880">
                    <input name="upload" type="file">
                    <span>
                        <?php printValue(TINYFEED_INTERFACE_IMGFILE_REMARK) ?>
                    </span>
                </label>

                <label>
                    <small>
                        <?php printValue(TINYFEED_INTERFACE_IMAGE_LABEL) ?>
                        <small>
                            <?php printSiteUrl() ?>
                        </small>
                    </small>
                    <input name="image"
                           type="text"
                           onblur="correctImageUrl()"
                           value="<?php printItemField('image', $params) ?>"
                           maxlength="250">
                    <span>
                        <?php printValue(TINYFEED_INTERFACE_IMAGE_REMARK) ?>
                    </span>
                </label>
            </fieldset>

            <button class="btn tools submit" name="submit" value="1" type="submit">
                <?php printValue(TINYFEED_INTERFACE_SUBMIT) ?>
            </button>

            <a class="btn tools cancel" href="<?php printSiteUrl() ?>news">
                <?php printValue(TINYFEED_INTERFACE_CANCEL) ?>
            </a>

         <?php                                          // -----------------
    }                                                   //
                                                        // -----------------
