<?php include TEMPLATE_PATH. "/include/header.php" ?>
<?php include TEMPLATE_PATH. "/admin/include/header.php" ?>

<script type="text/javascript" src="assets/js/ckeditor.js"></script>

      <script>
      // Prevents file upload hangs in Mac Safari
      // Inspired by http://airbladesoftware.com/notes/note-to-self-prevent-uploads-hanging-in-safari
      function closeKeepAlive() {
        if ( /AppleWebKit|MSIE/.test( navigator.userAgent) ) {
          var xhr = new XMLHttpRequest();
          xhr.open( "GET", "/ping/close", false );
          xhr.send();
        }
      }
      </script>

      <h1><?php echo $results['pageTitle']?></h1>

      <form action="admin.php?action=<?php echo $results['formAction']?>" method="post" enctype="multipart/form-data" onsubmit="closeKeepAlive()">
        <input type="hidden" name="articleId" value="<?php echo $results['article']->id ?>"/>

<?php if ( isset( $results['errorMessage'] ) ) { ?>
        <div class="errorMessage"><?php echo $results['errorMessage'] ?></div>
<?php } ?>

        <ul>

          <li>
            <label for="title">Article Title</label>
            <input type="text" name="title" id="title" placeholder="Name of the article" required autofocus maxlength="255" value="<?php echo htmlspecialchars( $results['article']->title )?>" />
          </li>

          <li>
            <label for="summary">Article Summary</label>
            <textarea name="summary" id="summary" placeholder="Brief description of the article" required maxlength="1000" style="height: 5em;"><?php echo htmlspecialchars( $results['article']->summary )?></textarea>
          </li>

          <li>
            <label for="content">Article Content</label>
            <textarea name="content" id="content" placeholder="The HTML content of the article" required maxlength="100000" style="height: 30em;"><?php echo htmlspecialchars( $results['article']->content ?? " ")?></textarea>
          </li>
<?php
$catID = $results['article']->categoryId ?? 0;
?>
          <li>
            <label for="categoryId">Article Category</label>
            <select name="categoryId" id="categoryId">
              <option value="0"<?php echo ($catID > 0) ? " selected" : ""?>>(none)</option>
            <?php foreach ( $results['categories'] as $category ) { ?>
              <option value="<?php echo $category->id?>"<?php echo ( $category->id == $catID ) ? " selected" : ""?>><?php echo htmlspecialchars( $category->name )?></option>
            <?php } ?>
            </select>
          </li>          
          
          <li>
            <label for="publicationDate">Publication Date</label>
            <input type="date" name="publicationDate" id="publicationDate" placeholder="YYYY-MM-DD" required maxlength="10" value="<?php echo $results['article']->publicationDate ? date( "Y-m-d", $results['article']->publicationDate ) : "" ?>" />
          </li>

          <?php if ( $results['article'] && $imagePath = $results['article']->getImagePath() ) { ?>
          <li>
            <label>Current Image</label>
            <img id="articleImage" src="<?php echo $imagePath ?>" alt="Article Image" />
          </li>

          <li>
            <label></label>
            <input type="checkbox" name="deleteImage" id="deleteImage" value="yes"/ > <label for="deleteImage">Delete</label>
          </li>
          <?php } ?>

          <li>
            <label for="image">New Image</label>
            <input type="file" name="image" id="image" placeholder="Choose an image to upload" maxlength="255" />
          </li>

        </ul>

        <div class="buttons">
          <input type="submit" name="saveChanges" value="Save Changes" />
          <input type="submit" formnovalidate name="cancel" value="Cancel" />
        </div>

      </form>

<?php if ( $results['article']->id ) { ?>
      <p><a href="admin.php?action=deleteArticle&amp;articleId=<?php echo $results['article']->id ?>" onclick="return confirm('Delete This Article?')">Delete This Article</a></p>
<?php } ?>

<script type="text/javascript">
class MyUploadAdapter {
    constructor(loader) {
        // The file loader instance to use during the upload.
        this.loader = loader;
    }

    // Starts the upload process.
    upload() {
        return this.loader.file
            .then(file => new Promise((resolve, reject) => {
                this._initRequest();
                this._initListeners(resolve, reject, file);
                this._sendRequest(file);
            }));
    }

    // Aborts the upload process.
    abort() {
        if (this.xhr) {
            this.xhr.abort();
        }
    }

    // Initializes the XMLHttpRequest object.
    _initRequest() {
        const xhr = this.xhr = new XMLHttpRequest();

        // Set the request URL.
        xhr.open('POST', 'upload.php', true);

        // Set up a progress listener to track the progress of the upload.
        xhr.upload.addEventListener('progress', evt => {
            if (evt.lengthComputable) {
                this.loader.uploadTotal = evt.total;
                this.loader.uploaded = evt.loaded;
            }
        });
    }

    // Initializes XMLHttpRequest listeners.
    _initListeners(resolve, reject, file) {
        const xhr = this.xhr;
        const loader = this.loader;
        const genericErrorText = `Couldn't upload file: ${file.name}.`;

        xhr.addEventListener('error', () => reject(genericErrorText));
        xhr.addEventListener('abort', () => reject());
        xhr.addEventListener('load', () => {
try {            
            const response = JSON.parse(xhr.response);
//            console.log(response);
            // Check if the upload was successful.
            if (!response || response.error) {
                alert(response.error);
                return reject(response && response.error ? response.error.message : genericErrorText);
            }
//console.info("Success!!!");
//console.info(response.url);
            // If the upload is successful, resolve the loader with the uploaded file's URL.
            resolve({
                default: response.url
            });
} catch (error) { 
    console.error('An error occurred:', error);
}
        });

        if (xhr.upload) {
            xhr.upload.addEventListener('progress', evt => {
                if (evt.lengthComputable) {
                    loader.uploadTotal = evt.total;
                    loader.uploaded = evt.loaded;
                }
            });
        }
    }

    // Sends the request to the server.
    _sendRequest(file) {
        const data = new FormData();

        // Append any additional parameters needed by your server.
        // data.append('param1', 'value1');

        // Append the file to the form data.
        data.append('upload', file);

        // Send the request.
        this.xhr.send(data);
    }
}

ClassicEditor
         .create( document.querySelector( '#content' ), {
//            toolbar: ['imageUpload', 'heading', '|', 'bold', 'italic', 'link']
         } )
         .then( editor => {
             editor.plugins.get('FileRepository').createUploadAdapter = loader => new MyUploadAdapter(loader);
             window.editor = editor;
         } )
         .catch( err => {
             console.error( err.stack );
         } );
</script>
      
<?php include TEMPLATE_PATH. "/include/footer.php";