<?php

/**
 * Shortcode to display Booking Form
 */
function contact_inquiry_form_shortcode() {
    ob_start();

    // Honeypot Field (hidden from real users)
    $honeypot = '<input type="text" name="company_name" style="display:none">';
    $rooms = [
        35 => 'Standard Single Room',
        50 => 'Standard Twin Room',
        53 => 'Deluxe Double Room',
        56 => 'Deluxe Triple Room',
    ];
    $room_name = $rooms[$room] ?? 'Unknown Room';
    
    // Handle Form Submission
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['contact_inquiry_submit'])) {
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $form_time = $_POST['form_time'] ?? time();
        $current_time = time();

        // Simple rate limit: 1 submission per 60 seconds
        if (($current_time - intval($form_time)) < 60) {
            echo '<div class="alert alert-danger">Please wait before submitting again.</div>';
        } elseif (!empty($_POST['company_name'])) {
            echo '<div class="alert alert-danger">Spam detected.</div>';
        } else {

    // Verify Google reCAPTCHA
    if (empty($_POST['g-recaptcha-response'])) {
        echo '<div class="alert alert-danger">Please verify that you are not a robot.</div>';
        return ob_get_clean();
    }

    $recaptcha_response = sanitize_text_field($_POST['g-recaptcha-response']);
    $secret_key = '6LfS-0IsAAAAANYTsvyW-ej_M1Ct-3TUWNRMWzi2';

    $verify_response = wp_remote_post(
        'https://www.google.com/recaptcha/api/siteverify',
        [
            'body' => [
                'secret'   => $secret_key,
                'response' => $recaptcha_response,
                'remoteip' => $_SERVER['REMOTE_ADDR']
            ]
        ]
    );

    if (is_wp_error($verify_response)) {
        echo '<div class="alert alert-danger">Captcha verification failed. Please try again.</div>';
        return ob_get_clean();
    }

    $response_body = json_decode(wp_remote_retrieve_body($verify_response), true);

    if (empty($response_body['success'])) {
        echo '<div class="alert alert-danger">Captcha verification failed. Please try again.</div>';
        return ob_get_clean();
    }

    // ✅ CAPTCHA PASSED — continue processing

            $full_name = sanitize_text_field($_POST['full_name']);
            $phone = sanitize_text_field($_POST['phone']);
            $email = sanitize_email($_POST['email']);
            $checkin = sanitize_text_field($_POST['checkin']);
            $checkout = sanitize_text_field($_POST['checkout']);
            $address = sanitize_text_field($_POST['address']);
            $guests = intval($_POST['guests']);
            $room = intval($_POST['room']);
            $message = sanitize_text_field($_POST['message']);
            $room_name = $rooms[$room] ?? 'Unknown Room';
            
            // Save submission as a custom post type
            $post_id = wp_insert_post([
                'post_title' => $full_name . ' - ' . $room_name,
                'post_type' => 'contact_inquiry',
                'post_status' => 'publish',
                'meta_input' => compact('full_name', 'email',  'phone', 'guests', 'checkin', 'checkout', 'room_name', 'address', 'message')
            ]);

            // Send Email Notification
            $to = 'booking@carnethotel.com';
            $subject = 'New Booking Request – CarNet Hotel';
            $message = "New Hotel Room Booking:\n\nName: $full_name\nEmail: $email\nPhone: $phone\nGuests: $guests\nCheck In: $checkin\nCheck Out: $checkout\nRooms: $room_name\nAddress: $address\n\nMessage:\n $message";
            wp_mail($to, $subject, $message);

            echo '<div class="alert alert-success">Thank you! Your booking has been received.</div>';
        }
    }

    ?> 
    <form method="post" class="contact_inquiry-form mt-4">
        <?php echo $honeypot; ?>
        <div class="card card-body shadow-sm" data-aos="fade-up">
            <div class="mb-4 alert alert-success">
                <h3 class="fw-bold">Book Your Stay at CarNet Hotel</h3>
                <p>
                    Fill out the form below to reserve your room. Our team will get back to you shortly to confirm your booking. 
                    For special requests or inquiries, feel free to call or email us directly.
                </p>
            </div>
            <div class="row">
                <input type="hidden" name="form_time" value="<?php echo time(); ?>">
                <div class="col-md-12 mb-3">
                    <label class="fw-bold">Name*</label>
                    <input type="text" name="full_name" class="form-control" placeholder="Full Name*" required>
                </div>
                <div class="col-md-12 mb-3">
                    <label class="fw-bold">Email*</label>
                    <input type="email" name="email" class="form-control" required>
                </div>
                <div class="col-md-8 mb-3">
                    <label class="fw-bold">Phone*</label>
                    <input type="text" name="phone" class="form-control" required>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="fw-bold">Number of Guests</label>
                    <input type="number" name="guests" class="form-control" min="1" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="fw-bold">Check-in Date*</label>
                    <input type="date" name="checkin" class="form-control" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="fw-bold">Check-out Date*</label>
                    <input type="date" name="checkout" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="fw-bold">Room Type*</label>
                    <select name="room" class="form-select" required>
                        <option value="">Select Room</option>
                        <?php foreach ( $rooms as $id => $label ) : ?>
                            <option value="<?php echo esc_attr( $id ); ?>"
                                <?php selected( $selected_room_id, $id ); ?>>
                                <?php echo esc_html( $label ); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-12 mb-3">
                    <label class="fw-bold">Address</label>
                    <input type="text" name="address" class="form-control" placeholder="City/Country">
                </div>
                <div class="col-md-12 mb-3">
                    <label class="fw-bold">Message</label>
                    <textarea class="form-text-area" name="message" rows="5" required></textarea>
                </div>
                <div class="col-md-12 mb-3 text-center">
                    <div class="g-recaptcha" data-sitekey="6Lf37kMsAAAAAIn7uBEtF0dEd7dUd_YmLTsXwcyL"></div>
                </div>

                <div class="col-md-12 mb-3 d-grid text-center">
                    <button type="submit" name="contact_inquiry_submit" class="btn btn-lg btn-danger">Book Now</button>
                </div>
        
            </div><!-- row !-->
        </div>
    </form>
    <style>
    .form-control, .form-select {
          height: 50px;
          border-radius: 15px;
          border: 1px solid rgba(var(--kpy-primary-rgb), 0.2);
        }
       .form-text-area{height:auto;border-radius: 15px;width:100%;display: block;padding:.375rem .75rem;background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;}
    </style>
    <?php
    return ob_get_clean();
}
add_shortcode('carnet_booking_form', 'contact_inquiry_form_shortcode');

// Register Custom Post Type for admin viewing
function contact_inquiry_cpt() {
    register_post_type('contact_inquiry', [
        'label' => 'Hotel Bookings',
        'public' => false,
        'show_ui' => true,
        'capability_type' => 'post',
        'supports' => ['title', 'custom-fields'],
        'menu_icon' => 'dashicons-forms',
    ]);
}
add_action('init', 'contact_inquiry_cpt');


