<?php
/**
 * Settings Controller
 *
 * REST API controller for plugin settings and event types
 *
 * @package NemtlyBooking
 * @since   PBOOKING_SINCE
 */

namespace NemtlyBooking\API;

use NemtlyBooking\Core\Container;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

/**
 * Settings Controller class
 *
 * Handles REST API endpoints for settings and event types
 *
 * @since PBOOKING_SINCE
 */
class Settings_Controller extends Nemtly_API {

    /**
     * Constructor
     *
     * @since PBOOKING_SINCE
     */
    public function __construct() {
        parent::__construct(); // This sets the namespace
        $this->rest_base = 'settings';
    }

    /**
     * Register REST API routes
     *
     * @since PBOOKING_SINCE
     */
    public function register_routes() {
        // Get all settings
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base,
            [
                'methods'             => 'GET',
                'callback'            => [ $this, 'get_settings' ],
                'permission_callback' => [ $this, 'check_admin_permissions' ],
            ]
        );

        // Update settings
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base,
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'update_settings' ],
                'permission_callback' => [ $this, 'check_admin_permissions' ],
                'args'                => $this->get_settings_schema(),
            ]
        );

        // Get event types
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/event-types',
            [
                'methods'             => 'GET',
                'callback'            => [ $this, 'get_event_types' ],
                'permission_callback' => [ $this, 'check_admin_permissions' ],
            ]
        );

        // Create custom template
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/templates',
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'create_template' ],
                'permission_callback' => [ $this, 'check_admin_permissions' ],
                'args'                => $this->get_template_schema(),
            ]
        );

        // Delete custom template
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/templates/(?P<template_id>[a-zA-Z0-9_-]+)',
            [
                'methods'             => 'DELETE',
                'callback'            => [ $this, 'delete_template' ],
                'permission_callback' => [ $this, 'check_admin_permissions' ],
            ]
        );

        // Create a WordPress page for a given plugin role (booking/events/dashboard).
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/create-page',
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'create_page_for_role' ],
                'permission_callback' => [ $this, 'check_admin_permissions' ],
                'args'                => [
                    'role' => [
                        'description' => __( 'Page role to create.', 'nemtly-booking' ),
                        'type'        => 'string',
                        'required'    => true,
                        'enum'        => [ 'dashboard' ],
                    ],
                ],
            ]
        );
    }

    /**
     * Get all settings
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Request object.
     *
     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function get_settings( $request ) {
        try {
            $settings_service = new \NemtlyBooking\Services\Settings_Service();
            $settings         = $settings_service->get_settings();

            $default_webhook_url = esc_url_raw(
                add_query_arg( 'action', 'nemtly_stripe_payment_response', home_url( '/' ) )
            );

            $settings['stripe_webhook_url_default'] = $default_webhook_url;

            if ( empty( $settings['stripe_webhook_url'] ) ) {
                $settings['stripe_webhook_url'] = $default_webhook_url;
            }

            return new WP_REST_Response(
                [
                    'success' => true,
                    'data'    => $settings,
                ],
                200
            );

        } catch ( \Exception $e ) {
            return new WP_Error(
                'settings_get_failed',
                $e->getMessage(),
                [ 'status' => 500 ]
            );
        }
    }

    /**
     * Update settings
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Request object.
     *
     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function update_settings( $request ) {
        try {
            $settings_service = new \NemtlyBooking\Services\Settings_Service();
            $settings_data    = $request->get_params();

            $result = $settings_service->update_settings( $settings_data );

            if ( is_wp_error( $result ) ) {
                return $result;
            }

            return new WP_REST_Response(
                [
                    'success' => true,
                    'message' => __( 'Settings updated successfully', 'nemtly-booking' ),
                    'data'    => $settings_service->get_settings(),
                ],
                200
            );

        } catch ( \Exception $e ) {
            return new WP_Error(
                'settings_update_failed',
                $e->getMessage(),
                [ 'status' => 500 ]
            );
        }
    }

    /**
     * Create (or reuse) the canonical page for a given plugin role and store
     * its ID in the matching plugin setting.
     *
     * Returns the updated settings object so the React client can sync both
     * its working and saved state without a full re-fetch (avoids a UI flicker
     * from toggling the global loading spinner).
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Request object.
     *
     * @return WP_REST_Response|WP_Error
     */
    public function create_page_for_role( $request ) {
        try {
            $role          = (string) $request->get_param( 'role' );
            $setup_service = new \NemtlyBooking\Services\Setup_Service();

            $result = $setup_service->create_page_for_role( $role );

            if ( is_wp_error( $result ) ) {
                return $result;
            }

            $settings_service = new \NemtlyBooking\Services\Settings_Service();

            return new WP_REST_Response(
                [
                    'success' => true,
                    'data'    => [
                        'page'     => $result,
                        'settings' => $settings_service->get_settings(),
                    ],
                ],
                201
            );

        } catch ( \Exception $e ) {
            return new WP_Error(
                'create_page_failed',
                $e->getMessage(),
                [ 'status' => 500 ]
            );
        }
    }

    /**
     * Get event types
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Request object.
     *
     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function get_event_types( $request ) {
        try {
            $event_types_service = new \NemtlyBooking\Services\Event_Types_Service();
            $event_types         = $event_types_service->get_all_event_types();

            return new WP_REST_Response(
                [
                    'success' => true,
                    'data'    => $event_types,
                ],
                200
            );

        } catch ( \Exception $e ) {
            return new WP_Error(
                'event_types_get_failed',
                $e->getMessage(),
                [ 'status' => 500 ]
            );
        }
    }

    /**
     * Create custom template
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Request object.
     *
     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function create_template( $request ) {
        try {
            $event_types_service = new \NemtlyBooking\Services\Event_Types_Service();
            $template_data       = $request->get_params();

            $result = $event_types_service->save_custom_template( $template_data );

            if ( is_wp_error( $result ) ) {
                return $result;
            }

            return new WP_REST_Response(
                [
                    'success'     => true,
                    'message'     => __( 'Template created successfully', 'nemtly-booking' ),
                    'template_id' => $result,
                    'data'        => $event_types_service->get_all_event_types(),
                ],
                201
            );

        } catch ( \Exception $e ) {
            return new WP_Error(
                'template_create_failed',
                $e->getMessage(),
                [ 'status' => 500 ]
            );
        }
    }

    /**
     * Delete custom template
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Request object.
     *
     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function delete_template( $request ) {
        try {
            $event_types_service = new \NemtlyBooking\Services\Event_Types_Service();
            $template_id         = $request->get_param( 'template_id' );

            $result = $event_types_service->delete_custom_template( $template_id );

            if ( is_wp_error( $result ) ) {
                return $result;
            }

            return new WP_REST_Response(
                [
                    'success' => true,
                    'message' => __( 'Template deleted successfully', 'nemtly-booking' ),
                    'data'    => $event_types_service->get_all_event_types(),
                ],
                200
            );

        } catch ( \Exception $e ) {
            return new WP_Error(
                'template_delete_failed',
                $e->getMessage(),
                [ 'status' => 500 ]
            );
        }
    }

    /**
     * Check admin permissions
     *
     * @since PBOOKING_SINCE
     *
     * @return bool True if user has admin permissions, false otherwise.
     */
    public function check_admin_permissions() {
        return current_user_can( 'manage_options' );
    }

    /**
     * Get settings schema for REST API
     *
     * @since PBOOKING_SINCE
     *
     * @return array Schema array.
     */
    private function get_settings_schema() {
        return [
            'timezone'                    => [
                'description' => __( 'Site timezone', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'email_notifications_enabled' => [
                'description' => __( 'Enable email notifications', 'nemtly-booking' ),
                'type'        => 'boolean',
                'required'    => false,
            ],
            'admin_email'                 => [
                'description'       => __( 'Admin email address', 'nemtly-booking' ),
                'type'              => 'string',
                'required'          => false,
                'sanitize_callback' => function ( $value ) {
                    return empty( $value ) ? '' : sanitize_email( $value );
                },
                'validate_callback' => function ( $value ) {
                    return empty( $value ) || is_email( $value );
                },
            ],
            'from_name'                   => [
                'description' => __( 'From name for emails', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'from_email'                  => [
                'description'       => __( 'From email address', 'nemtly-booking' ),
                'type'              => 'string',
                'required'          => false,
                'sanitize_callback' => function ( $value ) {
                    return empty( $value ) ? '' : sanitize_email( $value );
                },
                'validate_callback' => function ( $value ) {
                    return empty( $value ) || is_email( $value );
                },
            ],
            'confirmation_subject'        => [
                'description' => __( 'Confirmation email subject', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'confirmation_message'        => [
                'description' => __( 'Confirmation email message', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'reminder_enabled'            => [
                'description' => __( 'Enable reminder emails', 'nemtly-booking' ),
                'type'        => 'boolean',
                'required'    => false,
            ],
            'reminder_hours'              => [
                'description' => __( 'Reminder hours before event', 'nemtly-booking' ),
                'type'        => 'integer',
                'required'    => false,
            ],
            'reminder_subject'            => [
                'description' => __( 'Reminder email subject', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'reminder_message'            => [
                'description' => __( 'Reminder email message', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'accept_stripe'               => [
                'description' => __( 'Accept Stripe payments', 'nemtly-booking' ),
                'type'        => 'boolean',
                'required'    => false,
            ],
            'accept_manual_payment'       => [
                'description' => __( 'Accept manual/offline payments (e.g. bank transfer, cash)', 'nemtly-booking' ),
                'type'        => 'boolean',
                'required'    => false,
            ],
            'manual_payment_label'        => [
                'description' => __( 'Label for manual payment option (e.g. Bank transfer / Invoice)', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'manual_payment_instructions' => [
                'description' => __( 'Instructions shown to customer after choosing manual payment', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'google_client_id'            => [
                'description' => __( 'Google OAuth 2.0 Client ID', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'google_client_secret'        => [
                'description' => __( 'Google OAuth 2.0 Client Secret', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'google_calendar_id'          => [
                'description' => __( 'Google Calendar ID to sync bookings to', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],

            'dashboard_page_id'           => [
                'description'       => __( 'WordPress page hosting the customer dashboard shortcode', 'nemtly-booking' ),
                'type'              => 'integer',
                'required'          => false,
                'sanitize_callback' => 'absint',
                'validate_callback' => [ $this, 'validate_page_id' ],
            ],

            'business_hours'              => [
                'description' => __( 'Global default business hours for new slot-based events', 'nemtly-booking' ),
                'type'        => 'object',
                'required'    => false,
            ],

            'captcha_type'                => [
                'description' => __( 'CAPTCHA protection type', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
                'enum'        => [ 'disabled', 'text', 'turnstile' ],
            ],

            'turnstile_site_key'          => [
                'description' => __( 'Cloudflare Turnstile site key', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],

            'turnstile_secret_key'        => [
                'description' => __( 'Cloudflare Turnstile secret key', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
        ];
    }

    /**
     * Validate that a value is either 0 (cleared) or the ID of an existing
     * published WordPress page.
     *
     * @since PBOOKING_SINCE
     *
     * @param mixed $value Incoming value from the request.
     *
     * @return bool True if valid.
     */
    public function validate_page_id( $value ) {
        $page_id = absint( $value );

        if ( 0 === $page_id ) {
            return true;
        }

        $post = get_post( $page_id );

        return $post && 'page' === $post->post_type && 'publish' === $post->post_status;
    }

    /**
     * Get template schema for REST API
     *
     * @since PBOOKING_SINCE
     *
     * @return array Schema array.
     */
    private function get_template_schema() {
        return [
            'label'          => [
                'description' => __( 'Template name', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => true,
            ],
            'description'    => [
                'description' => __( 'Template description', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'icon'           => [
                'description' => __( 'Template icon', 'nemtly-booking' ),
                'type'        => 'string',
                'required'    => false,
            ],
            'duration'       => [
                'description' => __( 'Event duration in minutes', 'nemtly-booking' ),
                'type'        => 'integer',
                'required'    => true,
            ],
            'max_attendees'  => [
                'description' => __( 'Maximum number of attendees', 'nemtly-booking' ),
                'type'        => 'integer',
                'required'    => false,
            ],
            'buffer_before'  => [
                'description' => __( 'Buffer time in minutes before event', 'nemtly-booking' ),
                'type'        => 'integer',
                'required'    => false,
            ],
            'buffer_after'   => [
                'description' => __( 'Buffer time in minutes after event', 'nemtly-booking' ),
                'type'        => 'integer',
                'required'    => false,
            ],
            'booking_cutoff' => [
                'description' => __( 'Booking cutoff time in hours', 'nemtly-booking' ),
                'type'        => 'integer',
                'required'    => false,
            ],
            'allow_waitlist' => [
                'description' => __( 'Allow waitlist for events', 'nemtly-booking' ),
                'type'        => 'boolean',
                'required'    => false,
            ],
        ];
    }
}
