<?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\Controller\Content;

use function Vvveb\__;
use Vvveb\Controller\Listing;
use function Vvveb\humanReadable;
use function Vvveb\model;
use Vvveb\Sql\CommentSQL;
use Vvveb\System\CacheManager;
use Vvveb\System\Core\View;
use Vvveb\System\Images;
use Vvveb\System\User\Admin;

/**
 * Handles listing, saving, and deleting comments with status management.
 */
class Comments extends Listing {
	protected string $type = 'comment';

	protected string $list = 'comment';

	protected string $module = 'content';

	protected string $listController = 'comments';

	/**
	 * Deletes comments, checking user capabilities first.
	 *
	 * @return void
	 */
	public function delete(): void {
		$editCapability = 'edit_other_posts';

		if ($this->module == 'product') {
			$editCapability = 'edit_other_products';
		}

		if (Admin::hasCapability($editCapability)) {
			$this->userFilter = false;
		}

		parent::delete();
	}

	/**
	 * Changes the status of a comment (approve, spam, trash, etc.).
	 *
	 * @return void
	 */
	public function save(): void {
		$type       = $this->type;
		$comment_id = $this->request->get[$type . '_id'] ?? $this->request->post[$type . '_id'] ?? false;
		$status     = $this->request->get['newstatus'] ?? $this->request->post['newstatus'] ?? false;

		if ($comment_id) {
			$data = [$type => ['status' => (int) $status], $type . '_id' => $comment_id];

			$editCapability = 'edit_other_posts';

			if ($this->module == 'product') {
				$editCapability = 'edit_other_products';
			}

			if (Admin::hasCapability($editCapability)) {
				unset($data['admin_id']);
			} else {
				$data['admin_id'] = $this->global['admin_id'];
			}

			$comments = model($type);

			if ($comments->edit($data)) {
				//CacheManager::delete($type);
				CacheManager::delete();
				$this->view->success[] = sprintf(__('%s status changed!'), humanReadable(__($type)));
			}
		}

		$this->index();
	}

	/**
	 * Lists all comments with filtering by status and capability checks.
	 *
	 * @return void
	 */
	public function index(): void {
		$view           = View::getInstance();
		$type           = $this->type;
		$controller     = $this->controller ?? $type;
		$listController = $this->listController ?? $controller;
		$module         = $this->module;
		$list           = $this->list ?? $type . 's';
		$status         = $this->request->get['status'] ?? '';

		$comment_status = [
			0  => __('Pending'),
			1  => __('Approved'),
			2  => __('Spam'),
			3  => __('Trash'),
			-1 => __('All'),
		];

		$status   = $this->request->get['status'] ?? -1;
		//$comments = new CommentSQL();
		$comments = model($type);

		$options = [
			'type'         => $type,
		] + $this->global;
		unset($options['user_id']);

		if ($status > -1) {
			$options['status'] = $status;
		}

		$viewCapability = 'view_other_posts';
		if ($this->module == 'product') {
			$viewCapability = 'view_other_products';
		}

		if (Admin::hasCapability($viewCapability)) {
			unset($options['admin_id']);
		} else {
			$options['admin_id'] = $this->global['admin_id'];
		}

		$results        = $comments->getAll($options);
		$results[$type] = $results[$type] ?? [];

		foreach ($results[$type] as $id => &$comment) {
			if (isset($comment['image'])) {
				$comment['image'] = Images::image($comment['image'], $type);
			}

			if (isset($comment['avatar'])) {
				$comment['avatar'] = Images::image($comment['avatar'], 'user');
			}

			$url                    = ['module' => "$module/$listController", 'action' => 'save', 'status' => $status, $type . '_id' => $comment[$type . '_id']];
			$postUrl                = ['module' => "$module/$controller", $type . '_id' => $comment[$type . '_id']];

			$comment['author-url']  = '';
			if ($comment['user_id']) {
				$comment['author-url'] = \Vvveb\url(['module' => 'user/user', 'user_id' => $comment['user_id']]);
			}

			$comment['edit-url']    = \Vvveb\url($postUrl);
			$comment['delete-url']  = \Vvveb\url(['module' => "$module/$listController", 'action' => 'delete'] + $url);
			$comment['approve-url'] = \Vvveb\url(['newstatus' => 1] + $url);
			$comment['spam-url']    = \Vvveb\url(['newstatus' => 2] + $url);
			$comment['trash-url']   = \Vvveb\url(['newstatus' => 3] + $url);
		}

		$statuses                = "{$type}_status";
		$view->$list             = $results[$type];
		$view->count             = $results['count'];
		$view->$statuses         = $comment_status;
		$view->module            = $module;
		$view->controller        = $controller;

		$view->limit  = $options['limit'];
		$view->status = $status;
	}
}
