<?php
/**
 * RG Booking Widget - Date picker CTA for RMS Cloud booking engine
 *
 * Shortcode: [rg_booking_widget]
 * Attributes:
 *   - booking_url: Base booking engine URL (default from settings)
 *   - show_header: Show price header (yes/no, default: yes)
 *   - header_price: Price to display (default: "USD 899")
 *   - header_label: Label above price (default: "Best rate — book direct")
 *   - button_text: CTA button text (default: "Check Rates & Availability")
 *   - show_footer: Show benefits footer (yes/no, default: yes)
 *   - show_phone: Show phone number (yes/no, default: yes)
 *   - class: Additional CSS class
 */

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

/**
 * Register block and shortcode
 */
function rg_booking_widget_init() {
    // Register settings
    add_action( 'admin_menu', 'rg_booking_widget_settings_menu' );
    add_action( 'admin_init', 'rg_booking_widget_register_settings' );

    // Register shortcode
    add_shortcode( 'rg_booking_widget', 'rg_booking_widget_shortcode' );

    // Enqueue frontend assets
    add_action( 'wp_enqueue_scripts', 'rg_booking_widget_enqueue_assets' );
}
add_action( 'init', 'rg_booking_widget_init' );

/**
 * Add settings page
 */
function rg_booking_widget_settings_menu() {
    add_options_page(
        __( 'Booking Widget', 'theme' ),
        __( 'Booking Widget', 'theme' ),
        'manage_options',
        'rg-booking-widget',
        'rg_booking_widget_settings_page'
    );
}

/**
 * Register settings
 */
function rg_booking_widget_register_settings() {
    register_setting( 'rg_booking_widget_settings', 'rg_booking_widget_options', array(
        'type'              => 'array',
        'sanitize_callback' => 'rg_booking_widget_sanitize_options',
        'default'           => rg_booking_widget_defaults(),
    ) );
}

/**
 * Default options
 */
function rg_booking_widget_defaults() {
    return array(
        'booking_url'      => 'https://bookings13.rmscloud.com/Rates/Index/26185EB70D6D054B/90',
        'url_mode'         => 'rates', // 'rates' = A/D params, 'search' = Checkin/Nights params
        'arrival_param'    => 'A',
        'departure_param'  => 'D',
        'adults_param'     => 'Ad',
        'children_param'   => 'C',
        'date_format'      => 'MM/DD/YYYY',
        'phone_number'     => '+1 (877) 380-5750',
        'default_adults'   => 2,
        'default_children' => 0,
        'min_nights'       => 1,
    );
}

/**
 * Sanitize options
 */
function rg_booking_widget_sanitize_options( $input ) {
    $defaults = rg_booking_widget_defaults();
    $output   = array();

    $output['booking_url']      = esc_url_raw( $input['booking_url'] ?? $defaults['booking_url'] );
    $output['url_mode']         = in_array( $input['url_mode'] ?? '', array( 'rates', 'search' ), true ) ? $input['url_mode'] : $defaults['url_mode'];
    $output['arrival_param']    = sanitize_text_field( $input['arrival_param'] ?? $defaults['arrival_param'] );
    $output['departure_param']  = sanitize_text_field( $input['departure_param'] ?? $defaults['departure_param'] );
    $output['adults_param']     = sanitize_text_field( $input['adults_param'] ?? $defaults['adults_param'] );
    $output['children_param']   = sanitize_text_field( $input['children_param'] ?? $defaults['children_param'] );
    $output['date_format']      = sanitize_text_field( $input['date_format'] ?? $defaults['date_format'] );
    $output['phone_number']     = sanitize_text_field( $input['phone_number'] ?? $defaults['phone_number'] );
    $output['default_adults']   = absint( $input['default_adults'] ?? $defaults['default_adults'] );
    $output['default_children'] = absint( $input['default_children'] ?? $defaults['default_children'] );
    $output['min_nights']       = absint( $input['min_nights'] ?? $defaults['min_nights'] );

    return $output;
}

/**
 * Settings page
 */
function rg_booking_widget_settings_page() {
    $options  = get_option( 'rg_booking_widget_options', rg_booking_widget_defaults() );
    $defaults = rg_booking_widget_defaults();
    $options  = wp_parse_args( $options, $defaults );
    ?>
    <div class="wrap">
        <h1><?php esc_html_e( 'Booking Widget Settings', 'theme' ); ?></h1>

        <form method="post" action="options.php">
            <?php settings_fields( 'rg_booking_widget_settings' ); ?>

            <h2><?php esc_html_e( 'RMS Cloud Booking Engine', 'theme' ); ?></h2>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="booking_url"><?php esc_html_e( 'Base Booking URL', 'theme' ); ?></label></th>
                    <td>
                        <input type="url" id="booking_url" name="rg_booking_widget_options[booking_url]"
                               value="<?php echo esc_attr( $options['booking_url'] ); ?>" class="large-text">
                        <p class="description"><?php esc_html_e( 'The RMS Cloud booking engine URL (without parameters).', 'theme' ); ?></p>
                    </td>
                </tr>
            </table>

            <h2><?php esc_html_e( 'URL Parameters', 'theme' ); ?></h2>
            <p class="description"><?php esc_html_e( 'Configure the URL mode and parameter names used by RMS Cloud.', 'theme' ); ?></p>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="url_mode"><?php esc_html_e( 'URL Mode', 'theme' ); ?></label></th>
                    <td>
                        <select id="url_mode" name="rg_booking_widget_options[url_mode]">
                            <option value="rates" <?php selected( $options['url_mode'] ?? 'rates', 'rates' ); ?>>Rates Mode (A/D arrival+departure dates)</option>
                            <option value="search" <?php selected( $options['url_mode'] ?? 'rates', 'search' ); ?>>Search Mode (Checkin/Nights)</option>
                        </select>
                        <p class="description"><?php esc_html_e( 'Rates mode uses /Rates/Index/ with arrival & departure dates. Search mode uses /Search/Index/ with check-in & nights.', 'theme' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="date_format"><?php esc_html_e( 'Date Format', 'theme' ); ?></label></th>
                    <td>
                        <select id="date_format" name="rg_booking_widget_options[date_format]">
                            <option value="DD/MM/YYYY" <?php selected( $options['date_format'], 'DD/MM/YYYY' ); ?>>DD/MM/YYYY (e.g., 25/12/2026)</option>
                            <option value="MM/DD/YYYY" <?php selected( $options['date_format'], 'MM/DD/YYYY' ); ?>>MM/DD/YYYY (e.g., 12/25/2026)</option>
                            <option value="YYYY-MM-DD" <?php selected( $options['date_format'], 'YYYY-MM-DD' ); ?>>YYYY-MM-DD (e.g., 2026-12-25)</option>
                            <option value="DD-MMM-YYYY" <?php selected( $options['date_format'], 'DD-MMM-YYYY' ); ?>>DD-MMM-YYYY (e.g., 25-DEC-2026)</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="arrival_param"><?php esc_html_e( 'Arrival Date Parameter', 'theme' ); ?></label></th>
                    <td>
                        <input type="text" id="arrival_param" name="rg_booking_widget_options[arrival_param]"
                               value="<?php echo esc_attr( $options['arrival_param'] ?? 'A' ); ?>" class="regular-text">
                        <p class="description"><?php esc_html_e( 'Rates mode: A, Search mode: Checkin', 'theme' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="departure_param"><?php esc_html_e( 'Departure Date Parameter', 'theme' ); ?></label></th>
                    <td>
                        <input type="text" id="departure_param" name="rg_booking_widget_options[departure_param]"
                               value="<?php echo esc_attr( $options['departure_param'] ?? 'D' ); ?>" class="regular-text">
                        <p class="description"><?php esc_html_e( 'Rates mode: D (departure date), Search mode: Nights (number of nights)', 'theme' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="adults_param"><?php esc_html_e( 'Adults Parameter', 'theme' ); ?></label></th>
                    <td>
                        <input type="text" id="adults_param" name="rg_booking_widget_options[adults_param]"
                               value="<?php echo esc_attr( $options['adults_param'] ); ?>" class="regular-text">
                        <p class="description"><?php esc_html_e( 'Rates mode: Ad, Search mode: Adults', 'theme' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="children_param"><?php esc_html_e( 'Children Parameter', 'theme' ); ?></label></th>
                    <td>
                        <input type="text" id="children_param" name="rg_booking_widget_options[children_param]"
                               value="<?php echo esc_attr( $options['children_param'] ); ?>" class="regular-text">
                        <p class="description"><?php esc_html_e( 'Rates mode: Ch, Search mode: Children', 'theme' ); ?></p>
                    </td>
                </tr>
            </table>

            <h2><?php esc_html_e( 'Defaults', 'theme' ); ?></h2>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="default_adults"><?php esc_html_e( 'Default Adults', 'theme' ); ?></label></th>
                    <td>
                        <input type="number" id="default_adults" name="rg_booking_widget_options[default_adults]"
                               value="<?php echo esc_attr( $options['default_adults'] ); ?>" min="1" max="20" class="small-text">
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="default_children"><?php esc_html_e( 'Default Children', 'theme' ); ?></label></th>
                    <td>
                        <input type="number" id="default_children" name="rg_booking_widget_options[default_children]"
                               value="<?php echo esc_attr( $options['default_children'] ); ?>" min="0" max="20" class="small-text">
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="min_nights"><?php esc_html_e( 'Minimum Nights', 'theme' ); ?></label></th>
                    <td>
                        <input type="number" id="min_nights" name="rg_booking_widget_options[min_nights]"
                               value="<?php echo esc_attr( $options['min_nights'] ); ?>" min="1" max="30" class="small-text">
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="phone_number"><?php esc_html_e( 'Phone Number', 'theme' ); ?></label></th>
                    <td>
                        <input type="text" id="phone_number" name="rg_booking_widget_options[phone_number]"
                               value="<?php echo esc_attr( $options['phone_number'] ); ?>" class="regular-text">
                    </td>
                </tr>
            </table>

            <?php submit_button(); ?>
        </form>

        <hr>
        <h2><?php esc_html_e( 'Usage', 'theme' ); ?></h2>
        <h3><?php esc_html_e( 'Basic Shortcode', 'theme' ); ?></h3>
        <pre style="background:#f5f5f5;padding:15px;border-radius:4px;">[rg_booking_widget]</pre>

        <h3><?php esc_html_e( 'With Custom Header', 'theme' ); ?></h3>
        <pre style="background:#f5f5f5;padding:15px;border-radius:4px;">[rg_booking_widget header_price="USD 1,299" header_label="Premium Suite"]</pre>

        <h3><?php esc_html_e( 'Minimal (No Header/Footer)', 'theme' ); ?></h3>
        <pre style="background:#f5f5f5;padding:15px;border-radius:4px;">[rg_booking_widget show_header="no" show_footer="no" show_phone="no"]</pre>

        <h3><?php esc_html_e( 'All Attributes', 'theme' ); ?></h3>
        <table class="widefat" style="max-width:800px;">
            <thead>
                <tr>
                    <th><?php esc_html_e( 'Attribute', 'theme' ); ?></th>
                    <th><?php esc_html_e( 'Default', 'theme' ); ?></th>
                    <th><?php esc_html_e( 'Description', 'theme' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <tr><td><code>booking_url</code></td><td>(from settings)</td><td>Override the booking URL</td></tr>
                <tr><td><code>show_header</code></td><td>yes</td><td>Show price header section</td></tr>
                <tr><td><code>header_price</code></td><td>USD 899</td><td>Price to display</td></tr>
                <tr><td><code>header_label</code></td><td>Best rate — book direct</td><td>Label above price</td></tr>
                <tr><td><code>button_text</code></td><td>Check Rates &amp; Availability</td><td>CTA button text</td></tr>
                <tr><td><code>show_footer</code></td><td>yes</td><td>Show benefits footer</td></tr>
                <tr><td><code>show_phone</code></td><td>yes</td><td>Show phone number</td></tr>
                <tr><td><code>class</code></td><td></td><td>Additional CSS class</td></tr>
            </tbody>
        </table>
    </div>
    <?php
}

/**
 * Enqueue frontend assets
 */
function rg_booking_widget_enqueue_assets() {
    // Flatpickr for date picking
    wp_register_style(
        'flatpickr',
        'https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css',
        array(),
        '4.6.13'
    );
    wp_register_script(
        'flatpickr',
        'https://cdn.jsdelivr.net/npm/flatpickr',
        array(),
        '4.6.13',
        true
    );

    // Widget styles
    wp_register_style(
        'rg-booking-widget',
        get_stylesheet_directory_uri() . '/blocks/rg-booking-widget/style.css',
        array( 'flatpickr' ),
        '1.2.0'
    );

    // Widget script
    wp_register_script(
        'rg-booking-widget',
        get_stylesheet_directory_uri() . '/blocks/rg-booking-widget/script.js',
        array( 'flatpickr' ),
        '1.3.0',
        true
    );
}

/**
 * Shortcode handler
 */
function rg_booking_widget_shortcode( $atts ) {
    $options  = get_option( 'rg_booking_widget_options', rg_booking_widget_defaults() );
    $defaults = rg_booking_widget_defaults();
    $options  = wp_parse_args( $options, $defaults );

    $atts = shortcode_atts( array(
        'booking_url'  => $options['booking_url'],
        'show_header'  => 'yes',
        'header_price' => 'USD 899',
        'header_label' => 'Best rate — book direct',
        'header_per'   => 'per night · rates vary by season',
        'button_text'  => 'Check Rates & Availability',
        'show_footer'  => 'yes',
        'show_phone'   => 'yes',
        'class'        => '',
    ), $atts, 'rg_booking_widget' );

    // Enqueue assets
    wp_enqueue_style( 'rg-booking-widget' );
    wp_enqueue_script( 'rg-booking-widget' );

    // Pass config to JS
    wp_localize_script( 'rg-booking-widget', 'rgBookingConfig', array(
        'bookingUrl'      => esc_url( $atts['booking_url'] ),
        'urlMode'         => $options['url_mode'] ?? 'rates',
        'arrivalParam'    => $options['arrival_param'] ?? 'A',
        'departureParam'  => $options['departure_param'] ?? 'D',
        'adultsParam'     => $options['adults_param'] ?? 'Ad',
        'childrenParam'   => $options['children_param'] ?? 'C',
        'dateFormat'      => $options['date_format'] ?? 'MM/DD/YYYY',
        'defaultAdults'   => $options['default_adults'] ?? 2,
        'defaultChildren' => $options['default_children'] ?? 0,
        'minNights'       => $options['min_nights'] ?? 3,
    ) );

    $wrapper_class = 'rg-booking-widget';
    if ( ! empty( $atts['class'] ) ) {
        $wrapper_class .= ' ' . sanitize_html_class( $atts['class'] );
    }

    ob_start();
    ?>
    <div class="<?php echo esc_attr( $wrapper_class ); ?>">
        <div class="rg-booking-card">

            <?php if ( 'yes' === $atts['show_header'] ) : ?>
            <div class="rg-booking-card-header">
                <div class="rg-booking-from"><?php echo esc_html( $atts['header_label'] ); ?></div>
                <div class="rg-booking-price"><?php echo esc_html( $atts['header_price'] ); ?></div>
                <div class="rg-booking-per"><?php echo esc_html( $atts['header_per'] ); ?></div>
            </div>
            <?php endif; ?>

            <div class="rg-booking-card-body">
                <form class="rg-booking-form" data-booking-url="<?php echo esc_attr( $atts['booking_url'] ); ?>">

                    <div class="rg-booking-field-group">
                        <div class="rg-booking-field">
                            <label><?php esc_html_e( 'Check In', 'theme' ); ?></label>
                            <input type="text" class="rg-checkin-input" placeholder="<?php esc_attr_e( 'Select date', 'theme' ); ?>" readonly>
                        </div>
                        <div class="rg-booking-field">
                            <label><?php esc_html_e( 'Check Out', 'theme' ); ?></label>
                            <input type="text" class="rg-checkout-input" placeholder="<?php esc_attr_e( 'Select date', 'theme' ); ?>" readonly>
                        </div>
                    </div>

                    <div class="rg-guests-field">
                        <label><?php esc_html_e( 'Guests', 'theme' ); ?></label>
                        <div class="rg-guests-selector">
                            <input type="text" class="rg-guests-display" readonly
                                   value="<?php echo esc_attr( $options['default_adults'] . ' ' . _n( 'adult', 'adults', $options['default_adults'], 'theme' ) ); ?>"
                                   placeholder="<?php esc_attr_e( '2 adults', 'theme' ); ?>">
                            <div class="rg-guests-dropdown" style="display:none;">
                                <div class="rg-guest-row">
                                    <span class="rg-guest-label"><?php esc_html_e( 'Adults', 'theme' ); ?></span>
                                    <div class="rg-guest-controls">
                                        <button type="button" class="rg-guest-btn rg-guest-minus" data-target="adults">−</button>
                                        <span class="rg-guest-count" data-type="adults"><?php echo esc_html( $options['default_adults'] ); ?></span>
                                        <button type="button" class="rg-guest-btn rg-guest-plus" data-target="adults">+</button>
                                    </div>
                                </div>
                                <div class="rg-guest-row">
                                    <span class="rg-guest-label"><?php esc_html_e( 'Children', 'theme' ); ?></span>
                                    <div class="rg-guest-controls">
                                        <button type="button" class="rg-guest-btn rg-guest-minus" data-target="children">−</button>
                                        <span class="rg-guest-count" data-type="children"><?php echo esc_html( $options['default_children'] ); ?></span>
                                        <button type="button" class="rg-guest-btn rg-guest-plus" data-target="children">+</button>
                                    </div>
                                </div>
                                <button type="button" class="rg-guests-done"><?php esc_html_e( 'Done', 'theme' ); ?></button>
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="rg-booking-btn">
                        <?php echo esc_html( $atts['button_text'] ); ?>
                    </button>

                    <p class="rg-booking-note">
                        <?php esc_html_e( 'No booking fee', 'theme' ); ?> &nbsp;·&nbsp;
                        <?php esc_html_e( 'Best rate guaranteed', 'theme' ); ?>
                    </p>

                </form>
            </div>

            <?php if ( 'yes' === $atts['show_footer'] ) : ?>
            <div class="rg-booking-card-footer">
                <p><span class="rg-check-icon">✓</span> <?php esc_html_e( 'Free cancellation on flexible rates', 'theme' ); ?></p>
                <p><span class="rg-check-icon">✓</span> <?php esc_html_e( 'No credit card fee', 'theme' ); ?></p>
                <p><span class="rg-check-icon">✓</span> <?php esc_html_e( 'Exclusive member offers when you book direct', 'theme' ); ?></p>
            </div>
            <?php endif; ?>

            <?php if ( 'yes' === $atts['show_phone'] ) : ?>
            <div class="rg-booking-card-body" style="padding-top: 0;">
                <div class="rg-enquire-phone">
                    <p><?php esc_html_e( 'Prefer to book by phone?', 'theme' ); ?></p>
                    <a href="tel:<?php echo esc_attr( preg_replace( '/[^0-9+]/', '', $options['phone_number'] ) ); ?>">
                        📞 &nbsp;<?php echo esc_html( $options['phone_number'] ); ?>
                    </a>
                </div>
            </div>
            <?php endif; ?>

        </div>
    </div>
    <?php
    return ob_get_clean();
}
