<?php
/**
 * Admin Controller
 *
 * REST API controller for admin-specific endpoints and dashboard data
 *
 * @package NemtlyBooking
 * @since   PBOOKING_SINCE
 */

namespace NemtlyBooking\API;

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

/**
 * Admin Controller class
 *
 * Handles REST API endpoints for admin dashboard, settings, and analytics
 *
 * @since PBOOKING_SINCE
 */
class Admin_Controller extends Nemtly_API {

    /**
     * Rest base for the current object
     *
     * @var string
     */
    protected $rest_base = 'admin';

    /**
     * Dependency injection container
     *
     * @var Container
     */
    private $container;

    /**
     * Constructor
     *
     * @since PBOOKING_SINCE
     *
     * @param Container $container Dependency injection container.
     */
    public function __construct( Container $container ) {
        parent::__construct();
        $this->container = $container;
    }

    /**
     * Register the routes for admin endpoints
     *
     * @since PBOOKING_SINCE
     */
    public function register_routes() {
        // Dashboard data endpoint
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/dashboard',
            [
                [
                    'methods'             => \WP_REST_Server::READABLE,
                    'callback'            => [ $this, 'get_dashboard_data' ],
                    'permission_callback' => [ $this, 'check_admin_permissions' ],
                ],
            ]
        );

        // Analytics endpoint
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/analytics',
            [
                [
                    'methods'             => \WP_REST_Server::READABLE,
                    'callback'            => [ $this, 'get_analytics' ],
                    'permission_callback' => [ $this, 'check_admin_permissions' ],
                    'args'                => [
                        'period' => [
                            'type'        => 'string',
                            'default'     => '30days',
                            'enum'        => [ '7days', '30days', '90days', '1year' ],
                            'description' => __( 'Analytics period.', 'nemtly-booking' ),
                        ],
                    ],
                ],
            ]
        );

        // Settings management endpoint
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/settings',
            [
                [
                    'methods'             => \WP_REST_Server::READABLE,
                    'callback'            => [ $this, 'get_settings' ],
                    'permission_callback' => [ $this, 'check_admin_permissions' ],
                ],
                [
                    'methods'             => \WP_REST_Server::EDITABLE,
                    'callback'            => [ $this, 'update_settings' ],
                    'permission_callback' => [ $this, 'check_admin_permissions' ],
                    'args'                => $this->get_settings_args(),
                ],
            ]
        );

        // System status endpoint
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/system-status',
            [
                [
                    'methods'             => \WP_REST_Server::READABLE,
                    'callback'            => [ $this, 'get_system_status' ],
                    'permission_callback' => [ $this, 'check_admin_permissions' ],
                ],
            ]
        );

        // Export data endpoint
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/export',
            [
                [
                    'methods'             => \WP_REST_Server::CREATABLE,
                    'callback'            => [ $this, 'export_data' ],
                    'permission_callback' => [ $this, 'check_admin_permissions' ],
                    'args'                => [
                        'type'      => [
                            'type'        => 'string',
                            'required'    => true,
                            'enum'        => [ 'events', 'bookings', 'all' ],
                            'description' => __( 'Data type to export.', 'nemtly-booking' ),
                        ],
                        'format'    => [
                            'type'        => 'string',
                            'default'     => 'csv',
                            'enum'        => [ 'csv', 'json' ],
                            'description' => __( 'Export format.', 'nemtly-booking' ),
                        ],
                        'date_from' => [
                            'type'        => 'string',
                            'format'      => 'date',
                            'description' => __( 'Start date for export.', 'nemtly-booking' ),
                        ],
                        'date_to'   => [
                            'type'        => 'string',
                            'format'      => 'date',
                            'description' => __( 'End date for export.', 'nemtly-booking' ),
                        ],
                    ],
                ],
            ]
        );
    }

    /**
     * Get dashboard data
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Full details about the request.
     *
     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function get_dashboard_data( $request ) {
        try {
            $booking_service = $this->container->get( 'booking_service' );
            $event_service   = $this->container->get( 'event_service' );

            // Get statistics
            $stats = [
                'total_events'       => $this->get_total_events(),
                'total_bookings'     => $this->get_total_bookings(),
                'pending_bookings'   => $this->get_pending_bookings(),
                'confirmed_bookings' => $this->get_confirmed_bookings(),
                'cancelled_bookings' => $this->get_cancelled_bookings(),
            ];

            // Get recent activity
            $recent_activity = $this->get_recent_activity();

            // Get upcoming events
            $upcoming_events = $this->get_upcoming_events();

            // Get booking trends
            $booking_trends = $this->get_booking_trends();

            return rest_ensure_response(
                [
					'success' => true,
					'data'    => [
						'statistics'      => $stats,
						'recent_activity' => $recent_activity,
						'upcoming_events' => $upcoming_events,
						'booking_trends'  => $booking_trends,
					],
				]
            );
        } catch ( \Exception $e ) {
            return new WP_Error(
                'admin_dashboard_error',
                $e->getMessage(),
                [ 'status' => 500 ]
            );
        }
    }

    /**
     * Get analytics data
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Full details about the request.
     *
     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function get_analytics( $request ) {
        $period = $request->get_param( 'period' );

        try {
            $analytics = [
                'booking_stats'   => $this->get_booking_analytics( $period ),
                'event_stats'     => $this->get_event_analytics( $period ),
                'revenue_stats'   => $this->get_revenue_analytics( $period ),
                'popular_events'  => $this->get_popular_events( $period ),
                'booking_sources' => $this->get_booking_sources( $period ),
            ];

            return rest_ensure_response(
                [
					'success' => true,
					'data'    => $analytics,
				]
            );
        } catch ( \Exception $e ) {
            return new WP_Error(
                'admin_analytics_error',
                $e->getMessage(),
                [ 'status' => 500 ]
            );
        }
    }

    /**
     * Get settings
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Full details about the request.
     *
     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function get_settings( $request ) {
        try {
            $settings_service = $this->container->get( 'settings_service' );
            $settings         = $settings_service->get_all_settings();

            return rest_ensure_response(
                [
					'success' => true,
					'data'    => $settings,
				]
            );
        } catch ( \Exception $e ) {
            return new WP_Error(
                'admin_settings_error',
                $e->getMessage(),
                [ 'status' => 500 ]
            );
        }
    }

    /**
     * Update settings
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Full details about the request.
     *
     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function update_settings( $request ) {
        try {
            $settings_service = $this->container->get( 'settings_service' );
            $settings_data    = $request->get_json_params();

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

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

            return rest_ensure_response(
                [
					'success' => true,
					'message' => __( 'Settings updated successfully.', 'nemtly-booking' ),
				]
            );
        } catch ( \Exception $e ) {
            return new WP_Error(
                'admin_settings_update_error',
                $e->getMessage(),
                [ 'status' => 500 ]
            );
        }
    }

    /**
     * Get system status
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Full details about the request.
     *
     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function get_system_status( $request ) {
        try {
            $status = [
                'plugin_version'      => NEMTLY_BOOKING_VERSION,
                'wordpress_version'   => get_bloginfo( 'version' ),
                'php_version'         => PHP_VERSION,
                'database_version'    => $this->get_database_version(),
                'memory_limit'        => ini_get( 'memory_limit' ),
                'max_execution_time'  => ini_get( 'max_execution_time' ),
                'upload_max_filesize' => ini_get( 'upload_max_filesize' ),
                'post_max_size'       => ini_get( 'post_max_size' ),
                'active_theme'        => get_template(),
                'active_plugins'      => $this->get_active_plugins(),
                'database_tables'     => $this->check_database_tables(),
            ];

            return rest_ensure_response(
                [
					'success' => true,
					'data'    => $status,
				]
            );
        } catch ( \Exception $e ) {
            return new WP_Error(
                'admin_system_status_error',
                $e->getMessage(),
                [ 'status' => 500 ]
            );
        }
    }

    /**
     * Export data
     *
     * @since PBOOKING_SINCE
     *
     * @param WP_REST_Request $request Full details about the request.
     *
     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
     */
    public function export_data( $request ) {
        $type      = $request->get_param( 'type' );
        $format    = $request->get_param( 'format' );
        $date_from = $request->get_param( 'date_from' );
        $date_to   = $request->get_param( 'date_to' );

        try {
            $export_data = $this->prepare_export_data( $type, $date_from, $date_to );
            $filename    = $this->generate_export_filename( $type, $format );

            if ( 'csv' === $format ) {
                $this->export_csv( $export_data, $filename );
            } else {
                $this->export_json( $export_data, $filename );
            }

            return rest_ensure_response(
                [
					'success'  => true,
					'message'  => __( 'Export completed successfully.', 'nemtly-booking' ),
					'filename' => $filename,
				]
            );
        } catch ( \Exception $e ) {
            return new WP_Error(
                'admin_export_error',
                $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 arguments for validation
     *
     * @since PBOOKING_SINCE
     *
     * @return array Settings arguments.
     */
    private function get_settings_args() {
        return [
            'email_notifications_enabled' => [
                'type' => 'boolean',
            ],
            'admin_email'                 => [
                'type'   => 'string',
                'format' => 'email',
            ],
            'from_name'                   => [
                'type' => 'string',
            ],
            'from_email'                  => [
                'type'   => 'string',
                'format' => 'email',
            ],
            'confirmation_subject'        => [
                'type' => 'string',
            ],
            'confirmation_message'        => [
                'type' => 'string',
            ],
            'reminder_enabled'            => [
                'type' => 'boolean',
            ],
            'reminder_hours'              => [
                'type'    => 'integer',
                'minimum' => 1,
                'maximum' => 168,
            ],
            'reminder_subject'            => [
                'type' => 'string',
            ],
            'reminder_message'            => [
                'type' => 'string',
            ],
        ];
    }

    /**
     * Get total events count
     *
     * @since PBOOKING_SINCE
     *
     * @return int Total events count.
     */
    private function get_total_events() {
        $query = new \WP_Query(
            [
				'post_type'      => 'nemtly_event',
				'post_status'    => 'publish',
				'posts_per_page' => -1,
				'fields'         => 'ids',
			]
        );
        return $query->found_posts;
    }

    /**
     * Get total bookings count
     *
     * @since PBOOKING_SINCE
     *
     * @return int Total bookings count.
     */
    private function get_total_bookings() {
        global $wpdb;
        $table_name = nemtly_booking_get_bookings_table();
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table query, table name is controlled by plugin
        return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM `%s`', $table_name ) );
    }

    /**
     * Get pending bookings count
     *
     * @since PBOOKING_SINCE
     *
     * @return int Pending bookings count.
     */
    private function get_pending_bookings() {
        global $wpdb;
        $table_name = nemtly_booking_get_bookings_table();
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table query, table name is controlled by plugin
        return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM `%s` WHERE booking_status = %s', $table_name, 'pending' ) );
    }

    /**
     * Get confirmed bookings count
     *
     * @since PBOOKING_SINCE
     *
     * @return int Confirmed bookings count.
     */
    private function get_confirmed_bookings() {
        global $wpdb;
        $table_name = nemtly_booking_get_bookings_table();
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table query, table name is controlled by plugin
        return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM `%s` WHERE booking_status = %s', $table_name, 'confirmed' ) );
    }

    /**
     * Get cancelled bookings count
     *
     * @since PBOOKING_SINCE
     *
     * @return int Cancelled bookings count.
     */
    private function get_cancelled_bookings() {
        global $wpdb;
        $table_name = nemtly_booking_get_bookings_table();
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table query, table name is controlled by plugin
        return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM `%s` WHERE booking_status = %s', $table_name, 'cancelled' ) );
    }

    /**
     * Get recent activity
     *
     * @since PBOOKING_SINCE
     *
     * @return array Recent activity data.
     */
    private function get_recent_activity() {
        // Implementation for recent activity
        return [];
    }

    /**
     * Get upcoming events
     *
     * @since PBOOKING_SINCE
     *
     * @return array Upcoming events data.
     */
    private function get_upcoming_events() {
        // Implementation for upcoming events
        return [];
    }

    /**
     * Get booking trends
     *
     * @since PBOOKING_SINCE
     *
     * @return array Booking trends data.
     */
    private function get_booking_trends() {
        // Implementation for booking trends
        return [];
    }

    /**
     * Get booking analytics
     *
     * @since PBOOKING_SINCE
     *
     * @param string $period Analytics period.
     *
     * @return array Booking analytics data.
     */
    private function get_booking_analytics( $period ) {
        // Implementation for booking analytics
        return [];
    }

    /**
     * Get event analytics
     *
     * @since PBOOKING_SINCE
     *
     * @param string $period Analytics period.
     *
     * @return array Event analytics data.
     */
    private function get_event_analytics( $period ) {
        // Implementation for event analytics
        return [];
    }

    /**
     * Get revenue analytics
     *
     * @since PBOOKING_SINCE
     *
     * @param string $period Analytics period.
     *
     * @return array Revenue analytics data.
     */
    private function get_revenue_analytics( $period ) {
        // Implementation for revenue analytics
        return [];
    }

    /**
     * Get popular events
     *
     * @since PBOOKING_SINCE
     *
     * @param string $period Analytics period.
     *
     * @return array Popular events data.
     */
    private function get_popular_events( $period ) {
        // Implementation for popular events
        return [];
    }

    /**
     * Get booking sources
     *
     * @since PBOOKING_SINCE
     *
     * @param string $period Analytics period.
     *
     * @return array Booking sources data.
     */
    private function get_booking_sources( $period ) {
        // Implementation for booking sources
        return [];
    }

    /**
     * Get database version
     *
     * @since PBOOKING_SINCE
     *
     * @return string Database version.
     */
    private function get_database_version() {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Database version query, no user input
        return $wpdb->get_var( 'SELECT VERSION()' );
    }

    /**
     * Get active plugins
     *
     * @since PBOOKING_SINCE
     *
     * @return array Active plugins list.
     */
    private function get_active_plugins() {
        if ( ! function_exists( 'get_plugins' ) ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        $active_plugins = get_option( 'active_plugins', [] );
        return $active_plugins;
    }

    /**
     * Check database tables
     *
     * @since PBOOKING_SINCE
     *
     * @return array Database tables status.
     */
    private function check_database_tables() {
        global $wpdb;
        $table_name = nemtly_booking_get_bookings_table();
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Table existence check, table name is controlled by plugin
        $exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) ) === $table_name;
        return [
            'bookings_table' => $exists,
        ];
    }

    /**
     * Prepare export data
     *
     * @since PBOOKING_SINCE
     *
     * @param string $type Data type to export.
     * @param string $date_from Start date.
     * @param string $date_to End date.
     *
     * @return array Export data.
     */
    private function prepare_export_data( $type, $date_from, $date_to ) {
        // Implementation for export data preparation
        return [];
    }

    /**
     * Generate export filename
     *
     * @since PBOOKING_SINCE
     *
     * @param string $type Data type.
     * @param string $format Export format.
     *
     * @return string Filename.
     */
    private function generate_export_filename( $type, $format ) {
        $timestamp = gmdate( 'Y-m-d_H-i-s' );
        return "nemtly-booking-{$type}-{$timestamp}.{$format}";
    }

    /**
     * Export CSV data
     *
     * @since PBOOKING_SINCE
     *
     * @param array  $data Export data.
     * @param string $filename Filename.
     */
    private function export_csv( $data, $filename ) {
        // Implementation for CSV export
    }

    /**
     * Export JSON data
     *
     * @since PBOOKING_SINCE
     *
     * @param array  $data Export data.
     * @param string $filename Filename.
     */
    private function export_json( $data, $filename ) {
        // Implementation for JSON export
    }
}
