add_action('wp_ajax_save_booking','save_booking');
add_action('wp_ajax_nopriv_save_booking','save_booking');

function save_booking(){

    global $wpdb;

    // ================= SECURITY CHECK =================
    if(!check_ajax_referer('apricorn_nonce','nonce', false)){
        wp_send_json_error(['msg' => 'Security check failed']);
    }

    // ================= INPUT SAFE =================
    $name  = sanitize_text_field($_POST['name'] ?? '');
    $email = sanitize_email($_POST['email'] ?? '');
    $phone = sanitize_text_field($_POST['phone'] ?? '');
    $date  = sanitize_text_field($_POST['date'] ?? '');
    $coupon_code = sanitize_text_field($_POST['coupon'] ?? '');
    $payment_id  = sanitize_text_field($_POST['payment_id'] ?? '');

    // ================= JSON SAFE DECODE =================
    $tickets_raw = $_POST['tickets'] ?? '';
    $tickets = json_decode(stripslashes($tickets_raw), true);

    if(!is_array($tickets)){
        wp_send_json_error(['msg' => 'Invalid tickets format']);
    }

    // ================= VALIDATION =================
    if(empty($name) || empty($email) || empty($date) || empty($tickets)){
        wp_send_json_error(['msg' => 'Required fields missing']);
    }

    // ================= TOTAL CALC =================
    $total = 0;

    foreach($tickets as $key => $qty){

        $qty = intval($qty);
        if($qty <= 0) continue; // ❗ prevent negative/zero qty

        if(strpos($key,'ticket_') !== false){

            $id = intval(str_replace('ticket_','',$key));

            $row = $wpdb->get_row(
                $wpdb->prepare(
                    "SELECT id, price_weekday, price_weekend 
                     FROM {$wpdb->prefix}ticket_types 
                     WHERE id=%d",
                    $id
                )
            );

            if(!$row) continue;

            $day = date('w', strtotime($date));

            $price = ($day == 0 || $day == 6)
                ? $row->price_weekend
                : $row->price_weekday;

            $total += $price * $qty;
        }
    }

    // ================= COUPON =================
    $discount = 0;
    $coupon_id = null;

    if(!empty($coupon_code)){

        require_once APRICORN_PATH.'includes/coupon-functions.php';

        $validation = apricorn_validate_coupon(
            $coupon_code,
            get_current_user_id(),
            $total
        );

        if($validation['status']){

            $coupon = $validation['coupon'];
            $coupon_id = $coupon->id;

            $discount = apricorn_calculate_discount($coupon, $total);

            $total -= $discount;
        }
    }

    if($total < 0) $total = 0;

    // ================= SAVE BOOKING =================
    $inserted = $wpdb->insert($wpdb->prefix.'bookings',[
        'name'        => $name,
        'email'       => $email,
        'phone'       => $phone,
        'date'        => $date,
        'tickets'     => json_encode($tickets),
        'amount'      => $total,
        'payment_id'  => $payment_id,
        'created_at'  => current_time('mysql')
    ]);

    if(!$inserted){
        wp_send_json_error(['msg' => 'Booking insert failed']);
    }

    $booking_id = $wpdb->insert_id;

    // ================= COUPON USAGE =================
    $user_id = get_current_user_id();

    if($coupon_id && $user_id > 0){

        $wpdb->insert($wpdb->prefix.'coupon_usage',[
            'coupon_id'  => $coupon_id,
            'user_id'    => $user_id,
            'booking_id' => $booking_id,
            'used_at'    => current_time('mysql')
        ]);
    }

    // ================= SUCCESS RESPONSE =================
    wp_send_json_success([
        'msg'         => 'Booking saved successfully',
        'booking_id'  => $booking_id,
        'total'       => $total,
        'discount'    => $discount
    ]);

    wp_die();
}<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="https://thehillswaterpark.in/wp-sitemap-index.xsl" ?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><sitemap><loc>https://thehillswaterpark.in/wp-sitemap-posts-post-1.xml</loc></sitemap><sitemap><loc>https://thehillswaterpark.in/wp-sitemap-posts-post-2.xml</loc></sitemap><sitemap><loc>https://thehillswaterpark.in/wp-sitemap-posts-post-3.xml</loc></sitemap><sitemap><loc>https://thehillswaterpark.in/wp-sitemap-posts-post-4.xml</loc></sitemap><sitemap><loc>https://thehillswaterpark.in/wp-sitemap-posts-page-1.xml</loc></sitemap><sitemap><loc>https://thehillswaterpark.in/wp-sitemap-taxonomies-category-1.xml</loc></sitemap><sitemap><loc>https://thehillswaterpark.in/wp-sitemap-users-1.xml</loc></sitemap></sitemapindex>
