<?php
/**
 * app/plugins/blog/models/blog.php
 *
 * This class is used for the manipulation of the blog database table.
 *
 * @package TP Blog
 * @version 3.0
 * @author  Joey Kimsey <Joey@thetempusproject.com>
 * @link    https://TheTempusProject.com
 * @license https://opensource.org/licenses/MIT [MIT LICENSE]
 */
namespace TheTempusProject\Models;

use TheTempusProject\Canary\Bin\Canary as Debug;
use TheTempusProject\Bedrock\Functions\Check;
use TheTempusProject\Bedrock\Functions\Sanitize;
use TheTempusProject\Classes\DatabaseModel;
use TheTempusProject\TheTempusProject as App;
use TheTempusProject\Canary\Classes\CustomException;
use TheTempusProject\Houdini\Classes\Filters;
use TheTempusProject\Plugins\Comments as CommentPlugin;
use TheTempusProject\Models\Comments;

class Posts extends DatabaseModel {
    public $tableName = 'posts';
    public static $comments = false;

    public $databaseMatrix = [
        [ 'author', 'int', '11' ],
        [ 'created', 'int', '10' ],
        [ 'edited', 'int', '10' ],
        [ 'draft', 'int', '1' ],
        [ 'title', 'varchar', '86' ],
        [ 'slug', 'varchar', '64' ],
        [ 'content', 'text', '' ],
    ];

    public function __construct() {
        parent::__construct();
        if ( class_exists( 'TheTempusProject\Plugins\Comments' ) ) {
            $comments = new CommentPlugin;
            if ( $comments->checkEnabled() ) {
                self::$comments = new Comments;
            }
        }
    }

    public function newPost( $title, $post, $slug, $draft ) {
        if ( !Check::dataTitle( $title ) ) {
            Debug::info( 'modelBlog: illegal title.' );

            return false;
        }
        if ( $draft === 'saveDraft' ) {
            $draft = 1;
        } else {
            $draft = 0;
        }
        $fields = [
            'author' => App::$activeUser->ID,
            'draft' => $draft,
            'slug' => $slug,
            'created' => time(),
            'edited' => time(),
            'content' => Sanitize::rich( $post ),
            'title' => $title,
        ];
        if ( !self::$db->insert( $this->tableName, $fields ) ) {
            Debug::error( "Blog Post: $data not updated: $fields" );
            new customException( 'blogCreate' );

            return false;
        }
        return true;
    }

    public function updatePost( $id, $title, $content, $slug, $draft ) {
        if ( empty( self::$log ) ) {
            self::$log = new Log;
        }
        if ( !Check::id( $id ) ) {
            Debug::info( 'modelBlog: illegal ID.' );

            return false;
        }
        if ( !Check::dataTitle( $title ) ) {
            Debug::info( 'modelBlog: illegal title.' );

            return false;
        }
        if ( $draft === 'saveDraft' ) {
            $draft = 1;
        } else {
            $draft = 0;
        }
        $fields = [
            'draft' => $draft,
            'slug' => $slug,
            'edited' => time(),
            'content' => Sanitize::rich( $content ),
            'title' => $title,
        ];
        if ( !self::$db->update( $this->tableName, $id, $fields ) ) {
            new CustomException( 'blogUpdate' );
            Debug::error( "Blog Post: $id not updated: $fields" );

            return false;
        }
        self::$log->admin( "Updated Blog Post: $id" );
        return true;
    }

    public function preview( $title, $content ) {
        if ( !Check::dataTitle( $title ) ) {
            Debug::info( 'modelBlog: illegal characters.' );

            return false;
        }
        $fields = [
            'title' => $title,
            'content' => $content,
            'authorName' => App::$activeUser->username,
            'created' => time(),
        ];
        return (object) $fields;
    }

    public function filter( $postArray, $params = [] ) {
        foreach ( $postArray as $instance ) {
            if ( !is_object( $instance ) ) {
                $instance = $postArray;
                $end = true;
            }
            $draft = '';
            $authorName = self::$user->getUsername( $instance->author );

            // Summarize
            if ( ! empty( $instance->slug ) ) {
                $identifier = $instance->slug;
            } else {
                $identifier = $instance->ID;
            }

            $cleanPost = Sanitize::contentShort( $instance->content );
            // By Word
            $wordsArray = explode( ' ', $cleanPost );
            $wordSummary = implode( ' ', array_splice( $wordsArray, 0, 100 ) );
            // By Line
            $linesArray = explode( "\n", $cleanPost );
            $lineSummary = implode( "\n", array_splice( $linesArray, 0, 5 ) );

            if ( strlen( $wordSummary ) < strlen( $lineSummary ) ) {
                $contentSummaryNoLink = $wordSummary;
                $contentSummary = $wordSummary . '... <a href="{ROOT_URL}blog/post/' . $identifier . '" class="text-decoration-none">Read More</a>';
            } else {
                $contentSummaryNoLink = $lineSummary;
                $contentSummary = $lineSummary . '... <a href="{ROOT_URL}blog/post/' . $identifier . '" class="text-decoration-none">Read More</a>';
            }

            $instance->contentSummaryNoLink = $contentSummaryNoLink;
            $instance->contentSummary = $contentSummary;

            if ( isset( $params['stripHtml'] ) && $params['stripHtml'] === true ) {
                $instance->contentSummary = strip_tags( $instance->content );
            }
            if ( $instance->draft != '0' ) {
                $draft = ' <b>Draft</b>';
            }
            $instance->isDraft = $draft;
            $instance->authorName = $authorName;
            if ( self::$comments !== false ) {
                $instance->commentCount = self::$comments->count( 'blog', $instance->ID );
            }
            $instance->content = Filters::applyOne( 'mentions.0', $instance->content, true );
            $instance->content = Filters::applyOne( 'hashtags.0', $instance->content, true );

            $out[] = $instance;
            if ( !empty( $end ) ) {
                $out = $out[0];
                break;
            }
        }
        return $out;
    }

    public function archive( $includeDraft = false ) {
        $whereClause = [];
        $currentTimeUnix = time();
        $x = 0;
        $dataOut = [];
        $month = date( 'F', $currentTimeUnix );
        $year = date( 'Y', $currentTimeUnix );
        $previous = date( 'U', strtotime( "$month 1st $year" ) );
        if ( $includeDraft !== true ) {
            $whereClause = ['draft', '=', '0', 'AND'];
        }
        while ( $x <= 5 ) {
            $where = array_merge( $whereClause, ['created', '<=', $currentTimeUnix, 'AND', 'created', '>=', $previous] );
            $data = self::$db->get( $this->tableName, $where );
            $x++;
            $month = date( 'm', $previous );
            $montht = date( 'F', $previous );
            $year = date( 'Y', $previous );
            if ( !$data ) {
                $count = 0;
            } else {
                $count = $data->count();
            }
            $dataOut[] = (object) [
                'count' => $count,
                'month' => $month,
                'year' => $year,
                'monthText' => $montht,
            ];
            $currentTimeUnix = $previous;
            $previous = date( 'U', strtotime( '-1 months', $currentTimeUnix ) );
        }
        if ( !$data ) {
            Debug::info( 'No Blog posts found.' );

            return false;
        }
        return (object) $dataOut;
    }

    public function recent( $limit = null, $includeDraft = false ) {
        $whereClause = [];
        if ( $includeDraft !== true ) {
            $whereClause = ['draft', '=', '0'];
        } else {
            $whereClause = '*';
        }
        if ( empty( $limit ) ) {
            $postData = self::$db->get( $this->tableName, $whereClause );
        } else {
            $postData = self::$db->get( $this->tableName, $whereClause, 'ID', 'DESC', [0, $limit] );
        }
        if ( !$postData->count() ) {
            Debug::info( 'No Blog posts found.' );

            return false;
        }
        return $this->filter( $postData->results() );
    }

    public function listPosts( $params = [] ) {
        if ( isset( $params['includeDrafts'] ) && $params['includeDrafts'] === true ) {
            $whereClause = '*';
        } else {
            $whereClause = ['draft', '=', '0'];
        }
        $postData = self::$db->get( $this->tableName, $whereClause );
        if ( !$postData->count() ) {
            Debug::info( 'No Blog posts found.' );

            return false;
        }
        if ( isset( $params['stripHtml'] ) && $params['stripHtml'] === true ) {
            return $this->filter( $postData->results(), ['stripHtml' => true] );
        }
        return $this->filter( $postData->results() );
    }

    public function byYear( $year, $includeDraft = false ) {
        if ( !Check::id( $year ) ) {
            Debug::info( 'Invalid Year' );
            return false;
        }
        $whereClause = [];
        if ( $includeDraft !== true ) {
            $whereClause = ['draft', '=', '0', 'AND'];
        }
        $firstDayUnix = date( 'U', strtotime( "first day of $year" ) );
        $lastDayUnix = date( 'U', strtotime( "last day of $year" ) );
        $whereClause = array_merge( $whereClause, ['created', '<=', $lastDayUnix, 'AND', 'created', '>=', $firstDayUnix] );
        $postData = self::$db->get( $this->tableName, $whereClause );
        if ( !$postData->count() ) {
            Debug::info( 'No Blog posts found.' );

            return false;
        }
        return $this->filter( $postData->results() );
    }

    public function byAuthor( $ID, $includeDraft = false ) {
        if ( !Check::id( $ID ) ) {
            Debug::info( 'Invalid Author' );
            return false;
        }
        $whereClause = [];
        if ( $includeDraft !== true ) {
            $whereClause = ['draft', '=', '0', 'AND'];
        }
        $whereClause = array_merge( $whereClause, ['author' => $ID] );
        $postData = self::$db->get( $this->tableName, $whereClause );
        if ( !$postData->count() ) {
            Debug::info( 'No Blog posts found.' );

            return false;
        }
        return $this->filter( $postData->results() );
    }

    public function findBySlug( $slug, $includeDraft = false ) {
        $whereClause = [];
        if ( $includeDraft !== true ) {
            $whereClause = ['draft', '=', '0', 'AND'];
        }

        $whereClause = array_merge( $whereClause, ['slug', '=', $slug] );

        $postData = self::$db->get( $this->tableName, $whereClause );
        if ( !$postData->count() ) {
            Debug::info( 'No Blog posts found.' );
            return false;
        }
        return $this->filter( $postData->first() );
    }

    public function byMonth( $month, $year = 0, $includeDraft = false ) {
        if ( 0 === $year ) {
            $year = date( 'Y' );
        }
        if ( !Check::id( $month ) ) {
            Debug::info( 'Invalid Month' );
            return false;
        }
        if ( !Check::id( $year ) ) {
            Debug::info( 'Invalid Year' );
            return false;
        }
        $whereClause = [];
        if ( $includeDraft !== true ) {
            $whereClause = ['draft', '=', '0', 'AND'];
        }
        $firstDayUnix = date( 'U', strtotime( "$month/01/$year" ) );
        $month = date( 'F', $firstDayUnix );
        $lastDayUnix = date( 'U', strtotime( "last day of $month $year" ) );
        $whereClause = array_merge( $whereClause, ['created', '<=', $lastDayUnix, 'AND', 'created', '>=', $firstDayUnix] );
        $postData = self::$db->get( $this->tableName, $whereClause );
        if ( !$postData->count() ) {
            Debug::info( 'No Blog posts found.' );

            return false;
        }
        return $this->filter( $postData->results() );
    }
}
