<?php
/**
 * Booking Module
 *
 * Handles admin interface for managing bookings
 *
 * @since   PBOOKING_SINCE
 * @package Nemtly_Booking
 */

namespace NemtlyBooking\Modules\Booking;

use NemtlyBooking\Core\Container;
use NemtlyBooking\Core\Module;
use NemtlyBooking\Services\Booking_Service;

/**
 * Booking Module class
 *
 * @since PBOOKING_SINCE
 */
class Booking_Module extends Module {

    /**
     * Module name
     *
     * @var string
     */
    protected $name = 'booking';

    /**
     * Module dependencies
     *
     * @var array
     */
    protected $dependencies = [];

    /**
     * Booking service
     *
     * @var Booking_Service
     */
    private $booking_service;

    /**
     * Constructor
     *
     * @since PBOOKING_SINCE
     *
     * @param Container $container The dependency injection container.
     */
    public function __construct( Container $container ) {
        parent::__construct( $container );

        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
        add_action( 'wp_ajax_nemtly_booking_get_bookings', [ $this, 'ajax_get_bookings' ] );
        add_action( 'wp_ajax_nemtly_booking_update_status', [ $this, 'ajax_update_booking_status' ] );
        add_action( 'wp_ajax_nemtly_booking_delete', [ $this, 'ajax_delete_booking' ] );
    }

    /**
     * Initialize the module
     *
     * @since PBOOKING_SINCE
     */
    public function init() {
        // Get booking service from container
        $this->booking_service = $this->get_service( 'booking_service' );
    }

    /**
     * Render admin page
     *
     * @param String $hook the hook name.
     *
     * @since PBOOKING_SINCE
     */
    public function enqueue_admin_assets( $hook ) {
        // Enqueue assets for bookings page
        if ( 'nemtly-booking_page_nemtly-booking-bookings' === $hook ) {
            $this->enqueue_bookings_page_assets();
        }

        // Enqueue assets for statistics page
        if ( 'nemtly-booking_page_nemtly-booking-stats' === $hook ) {
            $this->enqueue_statistics_page_assets();
        }
    }

    /**
     * Enqueue assets for bookings page
     *
     * @since PBOOKING_SINCE
     */
    private function enqueue_bookings_page_assets() {
        // Enqueue admin bookings assets
        wp_enqueue_script(
            'nemtly-admin-bookings',
            NEMTLY_BOOKING_ASSETS . '/js/admin-bookings.js',
            [ 'jquery', 'wp-element', 'wp-components', 'wp-i18n', 'wp-api-fetch' ],
            NEMTLY_BOOKING_VERSION,
            true
        );

        wp_enqueue_style(
            'nemtly-admin-bookings',
            NEMTLY_BOOKING_ASSETS . '/css/admin-bookings.css',
            [],
            NEMTLY_BOOKING_VERSION
        );

        wp_localize_script(
            'nemtly-admin-bookings',
            'nemtlyBookingAdmin',
            [
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'api_url'  => rest_url( 'nemtly-booking/v1/' ),
				'nonce'    => wp_create_nonce( 'nemtly_booking_admin' ),
				'version'  => NEMTLY_BOOKING_VERSION,
                'strings'  => [
                    'loading'        => esc_html__( 'Loading...', 'nemtly-booking' ),
                    'processing'     => esc_html__( 'Processing...', 'nemtly-booking' ),
                    'error'          => esc_html__( 'An error occurred. Please try again.', 'nemtly-booking' ),
                    'success'        => esc_html__( 'Booking updated successfully.', 'nemtly-booking' ),
                    'no_bookings'    => esc_html__( 'No bookings found.', 'nemtly-booking' ),
                    'confirm_delete' => esc_html__( 'Are you sure you want to delete this booking?', 'nemtly-booking' ),
                    'no_selection'   => esc_html__( 'Please select at least one booking.', 'nemtly-booking' ),
                ],
            ]
        );
    }

    /**
     * Enqueue assets for statistics page
     *
     * @since PBOOKING_SINCE
     */
    private function enqueue_statistics_page_assets() {
        wp_enqueue_style(
            'nemtly-admin-statistics',
            NEMTLY_BOOKING_ASSETS . '/css/admin-statistics.css',
            [],
            NEMTLY_BOOKING_VERSION
        );
    }

    /**
     * Render bookings management page
     *
     * @since PBOOKING_SINCE
     */
    public function render_bookings_page() {
        // Check if we should use the React app
        $use_react_app = apply_filters( 'nemtly_booking_use_react_admin', true );

        if ( $use_react_app ) {
            // Render React app container
            ?>
            <div id="nemtly-booking-bookings-app" style="margin-left: -20px;"></div>
            <?php
        } else {
            // Fallback to PHP-based admin (existing code)

            // Verify nonce for search/filter operations
            if ( ( isset( $_GET['s'] ) && ! empty( $_GET['s'] ) ) ||
                ( isset( $_GET['status'] ) && ! empty( $_GET['status'] ) && 'all' !== $_GET['status'] ) ) {
                if ( ! isset( $_GET['nemtly_bookings_nonce'] ) ||
                    ! wp_verify_nonce( sanitize_key( $_GET['nemtly_bookings_nonce'] ), 'nemtly_bookings_search' ) ) {
                    wp_die( esc_html__( 'Security check failed', 'nemtly-booking' ) );
                }
            }

            // Validate and sanitize GET parameters
            $status   = '';
            $paged    = 1;
            $per_page = 20;

            // Validate status parameter
            if ( isset( $_GET['status'] ) ) {
                $status = sanitize_text_field( wp_unslash( $_GET['status'] ) );
                // Only allow valid status values
                $valid_statuses = [ 'pending', 'confirmed', 'cancelled', 'completed', '' ];
                if ( ! in_array( $status, $valid_statuses, true ) ) {
                    $status = '';
                }
            }

            // Validate pagination parameter
            if ( isset( $_GET['paged'] ) ) {
                $paged = absint( wp_unslash( $_GET['paged'] ) );
                if ( $paged < 1 ) {
                    $paged = 1;
                }
            }

            // Get bookings based on current filter
            $args = [
                'per_page' => $per_page,
                'page'     => $paged,
            ];

            if ( 'all' !== $status ) {
                $args['status'] = $status;
            }

            $bookings   = $this->booking_service->get_bookings( $args );
            $statistics = $this->booking_service->get_booking_statistics();

            include NEMTLY_BOOKING_DIR . 'includes/Modules/Booking/views/admin-bookings-page.php';
        }
    }

    /**
     * Render statistics page
     *
     * @since PBOOKING_SINCE
     */
    public function render_statistics_page() {
        $statistics = $this->booking_service->get_booking_statistics();

        include NEMTLY_BOOKING_DIR . 'includes/Modules/Booking/views/admin-statistics-page.php';
    }

    /**
     * Render admin page
     *
     * @since PBOOKING_SINCE
     */
    public function ajax_get_bookings() {
        // Verify nonce
        if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['_wpnonce'] ), 'nemtly_booking_admin' ) ) {
            wp_send_json_error( esc_html__( 'Security check failed', 'nemtly-booking' ) );
        }

        // Check permissions
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( esc_html__( 'You do not have permission to view bookings.', 'nemtly-booking' ) );
        }

        $page   = isset( $_POST['page'] ) ? absint( wp_unslash( $_POST['page'] ) ) : 1;
        $status = isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '';

        $args = [
            'page'   => $page,
            'status' => $status,
        ];

        $bookings = $this->booking_service->get_bookings( $args );

        if ( empty( $bookings ) ) {
            wp_send_json_error( esc_html__( 'No bookings found.', 'nemtly-booking' ) );
        }

        wp_send_json_success(
            [
                'bookings' => $bookings,
            ]
        );
    }

    /**
     * Update booking status via AJAX
     *
     * @since PBOOKING_SINCE
     */
    public function ajax_update_booking_status() {
        // Verify nonce
        if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['_wpnonce'] ), 'nemtly_booking_admin' ) ) {
            wp_send_json_error( esc_html__( 'Security check failed', 'nemtly-booking' ) );
        }

        // Check permissions
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( esc_html__( 'You do not have permission to update bookings.', 'nemtly-booking' ) );
        }

        $booking_id = isset( $_POST['booking_id'] ) ? absint( wp_unslash( $_POST['booking_id'] ) ) : 0;
        $status     = isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '';

        if ( ! $booking_id || ! $status ) {
            wp_send_json_error( esc_html__( 'Invalid booking ID or status.', 'nemtly-booking' ) );
        }

        $booking = $this->booking_service->get_booking( $booking_id );

        if ( ! $booking ) {
            wp_send_json_error( esc_html__( 'Booking not found.', 'nemtly-booking' ) );
        }

        $booking->set_booking_status( $status );
        $result = $this->booking_service->update_booking( $booking );

        if ( ! $result ) {
            wp_send_json_error( esc_html__( 'Failed to update booking status.', 'nemtly-booking' ) );
        }

        wp_send_json_success(
            [
                'message' => esc_html__( 'Booking status updated successfully.', 'nemtly-booking' ),
            ]
        );
    }

    /**
     * Handle AJAX request to delete a booking
     *
     * @since PBOOKING_SINCE
     */
    public function ajax_delete_booking() {
        // Verify nonce
        if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['_wpnonce'] ), 'nemtly_booking_admin' ) ) {
            wp_send_json_error( esc_html__( 'Security check failed', 'nemtly-booking' ) );
        }

        // Check permissions
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( esc_html__( 'You do not have permission to delete bookings.', 'nemtly-booking' ) );
        }

        $booking_id = isset( $_POST['booking_id'] ) ? absint( wp_unslash( $_POST['booking_id'] ) ) : 0;

        if ( ! $booking_id ) {
            wp_send_json_error( esc_html__( 'Invalid booking ID.', 'nemtly-booking' ) );
        }

        $result = $this->booking_service->delete_booking( $booking_id );

        if ( ! $result ) {
            wp_send_json_error( esc_html__( 'Failed to delete booking.', 'nemtly-booking' ) );
        }

        wp_send_json_success(
            [
                'message' => esc_html__( 'Booking deleted successfully.', 'nemtly-booking' ),
            ]
        );
    }
}
