<?php

namespace GemBoards\Ajax;

use GemBoards\Classes\AbstractAjaxHandler;
use GemBoards\Classes\Exception\GemboardsException;
use GemBoards\Classes\Exception\GemboardsInvalidArgumentException;
use GemBoards\Collections\FolderCollection;
use GemBoards\Utils\Helper;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Folder extends AbstractAjaxHandler {

	public function __construct() {
		$this->actions = [
			'create_folder' => [
				'callback'   => [ $this, 'create_folder' ],
				'permission' => 'update_projects',
				'fields'     => [
					'id'           => 'integer',
					'project_id'   => 'integer',
					'parent_id'    => 'integer',
					'folder_title' => 'string',
					'is_private'   => 'boolean',
				],
			],
			'get_folder'    => [
				'callback' => [ $this, 'get_folder' ],
				'fields'   => [ 'id' => 'integer' ],
			],
			'get_folders'   => [
				'callback' => [ $this, 'get_folders' ],
			],
			'delete_folder' => [
				'callback' => [ $this, 'delete_folder' ],
				'fields'   => [ 'id' => 'integer' ],
			],
		];
	}

	public function create_folder( $request ) {
		if ( ! isset( $request['project_id'], $request['folder_title'] ) ) {
			wp_send_json_error( [
				'message' => __( 'Project ID and Folder title are required.', 'gemboards' ),
			] );
		}


		$id      = $request['id'] ?? 0;
		$project = $request['project_id'];
		$parent  = $request['parent_id'] ?? null;
		$title   = $request['folder_title'];
		$private = Helper::string_to_bool( $request['is_private'] );

		if ( $id ) {
			$folder = Helper::get_folder( $id );
			if ( ! $folder ) {
				wp_send_json_error( [
					'message' => __( 'Invalid folder id.', 'gemboards' ),
				] );
			}
		} else {
			$folder = new \GemBoards\Entities\Folder();
		}

		$folder->set_project_id( $project );
		$folder->set_parent_id( $parent );
		$folder->set_title( $title );
		$folder->set_is_private( $private );
		$result = $folder->save();
		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [
				'message' => $result->get_error_message(),
			] );
		}

		wp_send_json_success( $this->get_folder_data( $folder ) );
	}

	public function get_folder( $request ) {
		$id = $request['id'] ?? 0;
		if ( empty( $id ) ) {
			wp_send_json_error( [ 'message' => __( 'Folder ID is required.', 'gemboards' ) ] );
		}

		if ( ! current_user_can( 'view_projects', [
			'project_id' => $id,
		] ) ) {
			wp_send_json_error( [ 'message' => __( 'You do not have permission to view this folder.', 'gemboards' ) ] );
		}

		$folder = Helper::get_folder( $id );
		if ( ! $folder ) {
			wp_send_json_error( [
				'message' => __( 'Invalid folder id.', 'gemboards' ),
			] );
		}

		wp_send_json_success( $this->get_folder_data( $folder ) );
	}

	public function get_folders() {
		try {
			$user_id = get_current_user_id();

			$args = [
				'per_page' => - 1,
			];
			if ( ! current_user_can( 'manage_gemboards' ) ) {
				$roles       = Helper::get_user_roles( $user_id );
				$project_ids = array_map( fn( $project ) => $project->get_object_id(), $roles );
				if ( empty( $project_ids ) ) {
					wp_send_json_success( [] );
				}

				$args['where'] = [
					[
						'key'     => 'project_id',
						'value'   => $project_ids,
						'compare' => 'IN',
					],
				];
			}

			$folders = new FolderCollection( $args );
			wp_send_json_success(
				array_map(
					fn( $folder ) => $this->get_folder_data( $folder ),
					$folders->get_results()
				)
			);
		} catch ( GemboardsInvalidArgumentException $e ) {
			wp_send_json_error( [
				'message' => 'Error fetching folders: ' . $e->getMessage(),
				'status'  => 500,
			] );
		}
	}

	public function delete_folder( $request ) {
		$id = $request['id'] ?? 0;
		if ( empty( $id ) ) {
			wp_send_json_error( [ 'message' => __( 'Folder ID is required.', 'gemboards' ) ] );
		}

		if ( ! current_user_can('update_projects', [ 'folder_id' => $id ]) ) {
			wp_send_json_error( [ 'message' => __( 'You do not have permission to delete this folder.', 'gemboards' ) ] );
		}

		$folder = Helper::get_folder( $id );
		if ( ! $folder ) {
			wp_send_json_error( [
				'message' => __( 'Invalid folder id.', 'gemboards' ),
			] );
		}
		try {
			$folder->delete();
			wp_send_json_success( [ 'message' => __( 'Folder deleted successfully.', 'gemboards' ) ] );
		} catch ( GemboardsException $e ) {
			wp_send_json_error( [ 'message' => $e->get_wp_error()->get_error_message() ] );
		}
	}

	private function get_folder_data( \GemBoards\Entities\Folder $folder ): array {
		return array_merge( $folder->get_data(), [
			'id'         => $folder->get_id(),
			'created_at' => $folder->get_date_created() ? $folder->get_date_created()->format( 'Y-m-d' ) : null,
			'updated_at' => $folder->get_date_updated() ? $folder->get_date_updated()->format( 'Y-m-d' ) : null,
		] );
	}
}
