<?php

/**
 * Vvveb
 *
 * Copyright (C) 2022  Ziadin Givan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

namespace Vvveb\Component;

use function Vvveb\get;
use function Vvveb\getSetting;
use function Vvveb\siteSettings;
use Vvveb\Sql\PostSQL;
use Vvveb\System\Component\ComponentBase;
use Vvveb\System\Event;
use Vvveb\System\Traits\Post;

class Posts extends ComponentBase {
	use Post;

	public static array $defaultOptions = [
		'page'               => ['url'],
		'post_id'            => 'url',
		'language_id'        => null,
		'source'             => 'autocomplete',
		'type'               => 'post',
		'site_id'            => null,
		'start'              => null,
		'limit'              => ['url', 4],
		'order_by'           => 'post_id',
		'direction'          => 'desc',
		'status'             => 'publish',
		'excerpt_limit'      => 200,
		'comment_count'      => 1,
		'comment_status'     => 1,
		'taxonomy_item_id'   => null,
		'taxonomy_item_slug' => null,
		'search'             => null,
		'search_boolean'     => null,
		'like'               => null,
		'admin_id'           => null,
		'month'              => null,
		'year'               => null,
		'image_size'         => 'medium',
		'categories'         => null,
		'tags'               => null,
		'taxonomy'           => null,
		'username'           => null,
		'date_format'        => null,
		'sticky'             => null,
		'404'                => null,
	];

	public array $options = [];

	/**
	 * Initialize posts component with module-specific option overrides.
	 *
	 * @param array<string, mixed> $options Component options.
	 */
	public function __construct(array $options = []) {
		parent::__construct($options);

		$module = \Vvveb\getModuleName();

		switch ($module) {
			case 'content/post':
				break;

			case 'content/category':
				if (isset($this->options['taxonomy_item_id']) && $this->options['taxonomy_item_id'] === 'page') {
					$this->options['taxonomy_item_id'] = get('taxonomy_item_id');
				}

				if (isset($this->options['taxonomy_item_slug']) && $this->options['taxonomy_item_slug'] === 'page') {
					$this->options['taxonomy_item_slug'] = get('slug');
				}

				break;
		}
	}

	/**
	 * Disable caching for search, pagination, or specific post lookups.
	 *
	 * @return string|null Parent cache key or null to disable caching.
	 */
	public function cacheKey(): ?string {
		if (isset($this->options['search']) || isset($this->options['page']) || isset($this->options['post_id'])) {
			return null;
		}

		return parent::cacheKey();
	}

	/**
	 * Get posts list with filtering, sticky posts, pagination, and 404 handling.
	 *
	 * @return array<string, mixed> Posts data with post list, limit, start, search, and archive info.
	 */
	public function results(): array {
		$posts = new PostSQL();

		$this->options['limit'] = (int) ($this->options['limit'] ?? 4 ?: 4);

		if (($page = $this->options['page'] ?? false) && is_numeric($page)) {
			$this->options['start'] = ($page - 1) * ($this->options['limit']);
		}

		$this->options['start'] = (int) ($this->options['start'] ?? 0 ?: 0);


		if (isset($this->options['post_id']) && is_array($this->options['post_id']) && $this->options['source'] === 'autocomplete') {
			$this->options['post_id'] = array_keys($this->options['post_id']);
		} else {
			$this->options['post_id'] = [];
		}

		if (isset($this->options['order_by']) &&
				! in_array($this->options['order_by'], ['post_id', 'admin_id', 'sort_order', 'parent', 'type', 'created_at', 'updated_at', 'slug', 'name'])) {
			unset($this->options['order_by']);
		}

		if (isset($this->options['direction']) &&
				! in_array($this->options['direction'], ['asc', 'desc'])) {
			unset($this->options['direction']);
		}

		//wildcard search for one word search
		if (isset($this->options['search']) && strpos($this->options['search'], ' ') === false) {
			$this->options['search_boolean'] = true;
		}

		if (isset($this->options['search']) && isset($this->options['search_boolean'])) {
			$this->options['search'] .= '*';
		}

		if (! isset($this->options['sticky'])) {
			$stickyPosts = getSetting('posts', 'sticky');
			$this->options['sticky'] = $stickyPosts;
		}

		//if only one taxonomy_item_id is provided then add it to array
		if (isset($this->options['taxonomy_item_id']) && ! is_array($this->options['taxonomy_item_id'])) {
			$this->options['taxonomy_item_id'] = [$this->options['taxonomy_item_id']];
		}

		$results = $posts->getAll($this->options);
		$this->options['type'] = $this->options['type'] ?: 'post';

		if (! isset($this->options['date_format'])) {
			$site = siteSettings();
			$this->options['date_format'] = $site['date_format'] ?? 'human';
		}

		if ($results && isset($results['post'])) {
			if ($this->options['sticky']) {
				$stickyOptions = $this->options;
				$stickyOptions['post_id'] = $this->options['sticky'];
				$stickyOptions['start'] = 0;
				unset($stickyOptions['limit']);
				$sticky = $posts->getAll($stickyOptions);

				if ($sticky && isset($sticky['post'])) {
					$results['post'] = $sticky['post'] + $results['post'];
				}
			}

			$this->posts($results['post'], $this->options);
		} else {
			$results['post'] = [];
		}

		//if archive then pass year and month
		if (isset($this->options['year'])) {
			$results['year'] = $this->options['year'];
		}

		if (isset($this->options['month'])) {
			$results['month'] = $this->options['month'];
		}

		$results['limit']  = $this->options['limit'];
		$results['start']  = $this->options['start'];
		$results['search'] = $this->options['search'] ?? '';

		if (! $results['post'] &&
			isset($this->options['page']) &&
			($this->options['page'] > 1) &&
			(isset($this->options['404']) && $this->options['404']) &&
			! ($_SERVER['QUERY_STRING'] ?? '')) {
			$results['404'] = true;
		}

		list($results) = Event :: trigger(__CLASS__,__FUNCTION__, $results);

		return $results;
	}

	/**
	 * Hide password-protected post content on each request.
	 *
	 * @param array<string, mixed> &$results Posts data to modify.
	 * @param int                  $index    Request index.
	 *
	 * @return void
	 */
	public function request(array &$results, int $index = 0): void {
		if (isset($results['post']) && $results['post']) {
			foreach ($results['post'] as &$post) {
				if ($post['password']) {
					$post['content']  = '';
					$post['excerpt']  = '';
					$post['image']  = PUBLIC_PATH . 'media/locked.svg';
				}
			}
		}
	}
}
