<?php

namespace GemBoards\Ajax;

use GemBoards\Classes\AbstractAjaxHandler;
use GemBoards\Classes\Exception\GemboardsException;
use GemBoards\Classes\Exception\GemboardsInvalidArgumentException;
use GemBoards\Collections\CardCollection;
use GemBoards\Entities\Column;
use GemBoards\Utils\Helper;

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

class Columns extends AbstractAjaxHandler {

	public function __construct() {
		$this->actions = [
			'create_column'                    => [
				'callback'   => [ $this, 'create_column' ],
				'permission' => 'manage_stages',
				'fields'     => [
					'id'           => 'integer',
					'column_title' => 'string',
					'board_id'     => 'integer',
					'column_slug'  => 'string',
					'column_color' => 'string',
					'sort_order'   => 'integer',
				],
			],
			'sort_column_order'                => [
				'callback'   => [ $this, 'sort_column_order' ],
				'permission' => 'manage_stages',
				'fields'     => [
					'column_id'  => 'integer',
					'sort_order' => 'integer',
				],
			],
			'get_column'                       => [
				'callback'   => [ $this, 'get_column' ],
				'permission' => 'manage_stages',
				'fields'     => [
					'column_id' => 'integer',
				],
			],
			'delete_column'                    => [
				'callback'   => [ $this, 'delete_column' ],
				'permission' => 'manage_stages',
				'fields'     => [
					'column_id' => 'integer',
				],
			],
			'get_available_column_sort_orders' => [
				'callback'   => [ $this, 'get_available_column_sort_orders' ],
				'permission' => 'view_projects',
				'fields'     => [
					'column_id' => 'integer',
				],
			],
			'archive_column_cards'             => [
				'callback'   => [ $this, 'archive_column_cards' ],
				'permission' => 'manage_stages',
				'fields'     => [
					'column_id' => 'integer',
				],
			],
			'delete_column_cards'              => [
				'callback'   => [ $this, 'delete_column_cards' ],
				'permission' => 'manage_stages',
				'fields'     => [
					'column_id' => 'integer',
				],
			],
		];
	}

	public function create_column( $request ) {
		if ( ! isset( $request['column_title'], $request['board_id'] ) ) {
			wp_send_json_error( [
				'message' => __( 'Column title and board ID are required.', 'gemboards' ),
			] );
		}

		$id          = $request['id'] ?? 0;
		$title       = $request['column_title'];
		$board_id    = $request['board_id'];
		$column_slug = $request['column_slug'] ?? sanitize_title( $title );
		$sort_order  = $request['sort_order'] ?? 0;
		$color       = $request['column_color'] ?? null;

		if ( $id ) {
			$column = Helper::get_column( $id );
			if ( ! $column ) {
				wp_send_json_error( [
					'message' => __( 'Invalid column id.', 'gemboards' ),
				] );
			}
		} else {
			$column = new Column();
		}

		$column->set_board_id( $board_id );
		$column->set_title( $title );
		$column->set_slug( $column_slug );
		$column->set_color( $color );
		$column->set_sort_order( $sort_order );
		$result = $column->save();
		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [
				'message' => $result->get_error_message(),
			] );
		}

		wp_send_json_success( $this->get_column_data( $column ) );
	}

	public function sort_column_order( $request ) {
		if ( ! isset( $request['column_id'] ) ) {
			wp_send_json_error( [
				'message' => 'Column ID is required.',
			] );
		}

		$column_id  = $request['column_id'];
		$sort_order = $request['sort_order'] ?? 1;

		$column = Helper::get_column( $column_id );
		if ( ! $column ) {
			wp_send_json_error( [
				'message' => __( 'Invalid column id.', 'gemboards' ),
			] );
		}
		$column->set_sort_order( $sort_order );
		$result = $column->save();
		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [
				'message' => $result->get_error_message(),
			] );
		}

		wp_send_json_success(
			$this->get_column_data( $column )
		);
	}

	public function get_column( $request ) {
		if ( ! isset( $request['column_id'] ) ) {
			wp_send_json_error( [
				'message' => 'Column ID is required.',
			] );
		}

		$column_id = $request['column_id'];
		$column    = Helper::get_column( $column_id );
		if ( ! $column ) {
			wp_send_json_error( [
				'message' => __( 'Invalid column id.', 'gemboards' ),
			] );
		}

		wp_send_json_success( $this->get_column_data( $column ) );
	}

	public function delete_column( $request ) {
		if ( ! isset( $request['column_id'] ) ) {
			wp_send_json_error( [
				'message' => __( 'Column ID is required.', 'gemboards' ),
			] );
		}

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

	public function get_available_column_sort_orders( array $payload ) {
		if ( empty( $payload['column_id'] ) ) {
			wp_send_json_error( [
				'message' => __( 'Column ID is required.', 'gemboards' ),
			] );
		}
		$column_id = absint( $payload['column_id'] );

		/** @var \GemBoards\Entities\Card[] $cards */
		$cards         = ( new CardCollection([
			'per_page' => -1,
			'where'    => [
				[
					'key'   => 'column_id',
					'value' => $column_id,
				],
			],
		]) )->get_results();
		$sort_orders   = array_unique( array_map( fn( $card) => $card->get_sort_order(), $cards ) );
		$sort_orders[] = ! empty( $sort_orders ) ? max( $sort_orders ) + 1 : 1;

		wp_send_json_success( $sort_orders );
	}

	public function archive_column_cards( array $payload ) {
		if ( ! isset( $payload['column_id'] ) ) {
			wp_send_json_error( [
				'message' => __( 'Column ID is required.', 'gemboards' ),
			] );
		}

		$id     = $payload['column_id'];
		$column = Helper::get_column( $id );
		if ( ! $column ) {
			wp_send_json_error( [
				'message' => __( 'Invalid column id.', 'gemboards' ),
			] );
		}

		try {
			/** @var \GemBoards\Entities\Card[] $cards */
			$cards = ( new CardCollection( [
				'per_page' => - 1,
				'where'    => [
					[
						'key'   => 'column_id',
						'value' => $id,
					],
				],
			] ) )->get_results();
			foreach ( $cards as $card ) {
				try {
					$card->set_archived( true );
					$result = $card->save();
					if ( is_wp_error( $result ) ) {
						Helper::error_log( $result->get_error_message() );
						continue;
					}
					do_action( 'gemboards/card/archived', $card );
				} catch ( GemboardsException $e ) {
					Helper::error_log( $e->getMessage() );
				}
			}
			wp_send_json_success( [ 'message' => __( 'Cards archived successfully.', 'gemboards' ) ] );
		} catch ( GemboardsInvalidArgumentException $e ) {
			Helper::error_log( $e->getMessage() );
			wp_send_json_error( [
				'message' => __( 'Error fetching cards.', 'gemboards' ),
			]);
		}
	}

	public function delete_column_cards( array $payload ) {
		if ( ! isset( $payload['column_id'] ) ) {
			wp_send_json_error( [
				'message' => __( 'Column ID is required.', 'gemboards' ),
			] );
		}

		$id     = $payload['column_id'];
		$column = Helper::get_column( $id );
		if ( ! $column ) {
			wp_send_json_error( [
				'message' => __( 'Invalid column id.', 'gemboards' ),
			] );
		}

		try {
			$cards = ( new CardCollection( [
				'per_page' => - 1,
				'where'    => [
					[
						'key'   => 'column_id',
						'value' => $id,
					],
				],
			] ) )->get_results();
			foreach ( $cards as $card ) {
				try {
					$card->delete();
				} catch ( GemboardsException $e ) {
					Helper::error_log( $e->getMessage() );
				}
			}
			wp_send_json_success( [ 'message' => __( 'Cards deleted successfully.', 'gemboards' ) ] );
		} catch ( GemboardsInvalidArgumentException $e ) {
			Helper::error_log( $e->getMessage() );
			wp_send_json_error( [
				'message' => __( 'Error fetching cards.', 'gemboards' ),
			]);
		}
	}

	private function get_column_data( Column $column ): array {
		return array_merge( $column->get_data(), [
			'id' => $column->get_id(),
		] );
	}
}
