<?php

namespace EmailCraft\App\Http\Controllers\Admin;

defined( "ABSPATH" ) || exit;

use EmailCraft\App\DTO\TemplateDTO;
use EmailCraft\App\DTO\TemplateReadDTO;
use EmailCraft\App\Repositories\TemplateRepository;
use EmailCraft\App\Http\Controllers\Controller;
use EmailCraft\WpMVC\Routing\Response;
use EmailCraft\WpMVC\RequestValidator\Validator;
use EmailCraft\WpMVC\Exceptions\Exception;
use WP_REST_Request;

class TemplateController extends Controller {
    public TemplateRepository $repository;

    public function __construct( TemplateRepository $repository ) {
        $this->repository = $repository;
    }

    /**
     * Display a listing of the resource.
     *
     * @param Validator $validator Instance of the Validator.
     * @param WP_REST_Request $request The REST request instance.
     * @return array
     */
    public function index( Validator $validator, WP_REST_Request $request ): array {
        $validator->validate(
            [
                "page"            => "required|numeric",
                "per_page"        => "numeric",
                "search"          => "string",
                "order_by"        => "string",
                "order_direction" => "string|accepted:asc,desc",
            ]
        );

        $dto = ( new TemplateReadDTO )->set_page( $request->get_param( "page" ) )
            ->set_per_page( (int) $request->get_param( "per_page" ) )
            ->set_search( (string) $request->get_param( "search" ) )
            ->set_order_by( (string) $request->get_param( "order_by" ) ?? 'ID' )
            ->set_order_direction( (string) $request->get_param( "order_direction" ) ?? 'desc' );

        return Response::send( $this->repository->get( $dto ) );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Validator $validator Instance of the Validator.
     * @param WP_REST_Request $request The REST request instance.
     * @return array
     */
    public function store( Validator $validator, WP_REST_Request $request ): array {
        $validator->validate(
            [
                'title'         => 'required|string',
                'integration'   => 'required|string',
                'template_type' => 'required|string',
                'template'      => 'required|string',
            ]
        );

        $dto = ( new TemplateDTO )->set_title( $request->get_param( "title" ) )
            ->set_integration( $request->get_param( "integration" ) )
            ->set_template_type( $request->get_param( "template_type" ) );

        $path                  = emailcraft_dir( 'app/templates/' . $request->get_param( "integration" ) . '/' . $request->get_param( "template_type" ) . '/' . $request->get_param( "template" ) );
        $template_content_path = $path . '/content.txt';

        if ( is_file( $template_content_path ) ) {
            $content = file_get_contents( $template_content_path );
            $dto->set_content( $content );
        }

        $id = $this->repository->create( $dto );

        $settings_path = $path . '/settings.json';

        if ( is_file( $settings_path ) ) {
            $content = file_get_contents( $settings_path );
            add_post_meta( $id, '_emailcraft_settings', json_decode( $content, true ) );
        }

        return Response::send(
            [
                "message" => esc_html__( "Item was created successfully", 'emailcraft' ),
                "data"    => [
                    "id" => $id
                ]
            ], 201
        );
    }

    public function updateStatus( Validator $validator, WP_REST_Request $request ): array {
        $validator->validate(
            [
                "id"    => "required|numeric",
                "value" => "required|boolean"
            ]
        );

        wp_update_post(
            [
                "ID"          => $request->get_param( "id" ),
                "post_status" => $request->get_param( "value" ) ? "publish" : "draft",
            ]
        );

        return Response::send(
            [
                "message" => esc_html__( "Template status was updated successfully", 'emailcraft' )
            ]
        );
    }

    // /**
    //  * Display the specified resource.
    //  *
    //  * @param Validator $validator Instance of the Validator.
    //  * @param WP_REST_Request $request The REST request instance.
    //  * @return array
    //  * @throws Exception
    //  */
    // public function show( Validator $validator, WP_REST_Request $request ): array {
    //     $validator->validate(
    //         [
    //             "id" => "required|numeric"
    //         ]
    //     );

    //     $item = $this->repository->get_by_id( $request->get_param( "id" ) );

    //     if ( ! $item ) {
    //         throw new Exception( esc_html__( "Item not found" ) );
    //     }

    //     return Response::send(
    //         [
    //             "data" => $item
    //         ]
    //     );
    // }

    // /**
    //  * Update the specified resource in storage.
    //  *
    //  * @param Validator $validator Instance of the Validator.
    //  * @param WP_REST_Request $request The REST request instance.
    //  * @return array
    //  */
    // public function update( Validator $validator, WP_REST_Request $request ): array {
    //     $validator->validate(
    //         [
    //             "id" => "required|numeric"
    //             // Add other validation rules as needed.
    //         ]
    //     );

    //     $dto = new YourDTO;
    //     $dto->set_id( $request->get_param( "id" ) );

    //     $this->repository->update( $dto );

    //     return Response::send(
    //         [
    //             "message" => esc_html__( "Item was updated successfully" )
    //         ]
    //     );
    // }

    /**
     * Remove the specified resource from storage.
     *
     * @param Validator $validator Instance of the Validator.
     * @param WP_REST_Request $request The REST request instance.
     * @return array
     */
    public function delete( Validator $validator, WP_REST_Request $request ): array {
        $validator->validate(
            [
                "id" => "required|numeric"
            ]
        );

        $this->repository->delete_by_id( $request->get_param( "id" ) );

        return Response::send(
            [
                "message" => esc_html__( "Item was deleted successfully", 'emailcraft' )
            ]
        );
    }
}