<?php
/**
 * Demo import for Adventure Block.
 */

add_action( 'wp_ajax_adventure_block_run_demo_import', 'adventure_block_run_demo_import' );

function adventure_block_create_demo_trips() {

    if ( ! class_exists( 'WP_Travel' ) ) {
        return new WP_Error( 'wp_travel_missing', 'WP Travel plugin is not active.' );
    }

    if ( ! post_type_exists( 'itineraries' ) ) {
        return new WP_Error( 'post_type_missing', 'Itineraries post type not found.' );
    }

    $trips = array(
        array(
            'title'    => 'Windsor Castle',
            'price'    => '85.00',
            'days'     => '4 Days',
            'location' => 'Greenwood',
            'people'   => '20',
            'image'    => get_theme_file_path() . '/images/destination-1.png',
        ),
        array(
            'title'    => 'Big Ben',
            'price'    => '85.00',
            'days'     => '4 Days',
            'location' => 'Eagle Ridge',
            'people'   => '20',
            'image'    => get_theme_file_path() . '/images/destination-2.png',
        ),
        array(
            'title'    => 'Edinburg Castle',
            'price'    => '85.00',
            'days'     => '4 Days',
            'location' => 'Eagle Cliff',
            'people'   => '20',
            'image'    => get_theme_file_path() . '/images/destination-3.png',
        ),
    );

    require_once ABSPATH . 'wp-admin/includes/image.php';
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';

    foreach ( $trips as $trip ) {

        // Prevent duplicate imports
        $existing = get_page_by_title( $trip['title'], OBJECT, 'itineraries' );

        if ( $existing ) {
            continue;
        }

        $trip_id = wp_insert_post(
            array(
                'post_title'   => $trip['title'],
                'post_content' => 'Demo trip created by Adventure Block.',
                'post_status'  => 'publish',
                'post_type'    => 'itineraries',
            ),
            true
        );

        if ( is_wp_error( $trip_id ) ) {
            error_log( 'Trip creation failed: ' . $trip_id->get_error_message() );
            continue;
        }

        // WP Travel meta
        update_post_meta( $trip_id, 'wp_travel_price', $trip['price'] );
        update_post_meta( $trip_id, 'wp_travel_trip_price', $trip['price'] );
        update_post_meta( $trip_id, 'wp_travel_pricing_option_type', 'multiple-price' );
        update_post_meta( $trip_id, 'wp_travel_enable_pricing_options', 'yes' );
        update_post_meta( $trip_id, 'wp_travel_price_per', 'person' );
        update_post_meta( $trip_id, 'wp_travel_group_size', $trip['people'] );
        update_post_meta( $trip_id, 'wp_travel_location', $trip['location'] );
        update_post_meta( $trip_id, 'wp_travel_lat', '0' );
        update_post_meta( $trip_id, 'wp_travel_lng', '0' );
        update_post_meta( $trip_id, 'wp_travel_trip_map_use_lat_lng', '1' );

        $pricing_category_id = adventure_block_get_wp_travel_pricing_category_term_id();
        if ( ! empty( $pricing_category_id ) && class_exists( 'WP_Travel_Helpers_Pricings' ) ) {
            $min_pax = 1;
            $max_pax = absint( $trip['people'] );
            $pricing_data = array(
                'title'          => 'Default Price',
                'max_pax'        => $max_pax,
                'min_pax'        => $min_pax,
                'has_group_price'=> 0,
                'group_prices'   => array(),
                'categories'     => array(
                    array(
                        'id'                 => $pricing_category_id,
                        'price_per'          => 'person',
                        'regular_price'      => $trip['price'],
                        'is_sale'            => 0,
                        'sale_price'         => 0,
                        'is_sale_percentage' => 0,
                        'has_group_price'    => 0,
                        'group_prices'       => array(),
                        'default_pax'        => 0,
                        'term_info'          => array(
                            'id'       => $pricing_category_id,
                            'title'    => 'Adult',
                            'pax_size' => 1,
                        ),
                    ),
                ),
                'trip_extras'     => array(),
            );
            WP_Travel_Helpers_Pricings::update_pricings( $trip_id, array( $pricing_data ) );
            update_post_meta( $trip_id, 'wp_travel_pricing_options', array( $pricing_data ) );
        }

        if ( taxonomy_exists( 'travel_locations' ) ) {
            $location_term = term_exists( $trip['location'], 'travel_locations' );
            if ( ! $location_term ) {
                $location_term = wp_insert_term( $trip['location'], 'travel_locations' );
            }
            if ( ! is_wp_error( $location_term ) ) {
                $term_id = 0;
                if ( is_array( $location_term ) && isset( $location_term['term_id'] ) ) {
                    $term_id = (int) $location_term['term_id'];
                } elseif ( is_int( $location_term ) || ctype_digit( (string) $location_term ) ) {
                    $term_id = (int) $location_term;
                }

                if ( ! empty( $term_id ) ) {
                    wp_set_post_terms( $trip_id, array( $term_id ), 'travel_locations', false );
                }
            }
        }

        $duration_days = intval( $trip['days'] );
        update_post_meta( $trip_id, 'wp_travel_trip_duration', $duration_days );
        update_post_meta( $trip_id, 'wp_travel_trip_duration_night', 0 );

        // Featured Image
        if ( file_exists( $trip['image'] ) ) {

            $upload = wp_upload_bits(
                basename( $trip['image'] ),
                null,
                file_get_contents( $trip['image'] )
            );

            if ( empty( $upload['error'] ) ) {

                $attachment = array(
                    'post_mime_type' => wp_check_filetype( $upload['file'] )['type'],
                    'post_title'     => sanitize_file_name( basename( $upload['file'] ) ),
                    'post_content'   => '',
                    'post_status'    => 'inherit',
                );

                $attachment_id = wp_insert_attachment(
                    $attachment,
                    $upload['file'],
                    $trip_id
                );

                if ( ! is_wp_error( $attachment_id ) ) {

                    $attach_data = wp_generate_attachment_metadata(
                        $attachment_id,
                        $upload['file']
                    );

                    wp_update_attachment_metadata(
                        $attachment_id,
                        $attach_data
                    );

                    set_post_thumbnail(
                        $trip_id,
                        $attachment_id
                    );
                }
            }
        }

        error_log( 'Trip created successfully: ' . $trip_id );
    }

    update_option( 'adventure_block_demo_import_completed', true );

    return true;
}

if ( ! function_exists( 'adventure_block_import_demo_products_data' ) ) {
    /**
     * Compatibility callback for TGMPA plugin activation demo import.
     */
    function adventure_block_import_demo_products_data() {
        return adventure_block_create_demo_trips();
    }
}

function adventure_block_run_demo_import() {

    check_ajax_referer(
        'adventure_block_demo_nonce',
        'nonce'
    );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( 'Permission denied.' );
    }

    $result = adventure_block_create_demo_trips();

    if ( is_wp_error( $result ) ) {
        wp_send_json_error( $result->get_error_message() );
    }

    wp_send_json_success( 'WP Travel demo trips imported successfully.' );
}

/**
 * Get or create an Adult pricing category term for WP Travel.
 *
 * @return int Pricing category term ID.
 */
function adventure_block_get_wp_travel_pricing_category_term_id() {
    if ( ! taxonomy_exists( 'itinerary_pricing_category' ) ) {
        return 0;
    }

    $term = term_exists( 'Adult', 'itinerary_pricing_category' );
    if ( ! $term ) {
        $term = wp_insert_term(
            'Adult',
            'itinerary_pricing_category',
            array(
                'slug' => 'adult',
            )
        );
    }

    if ( is_wp_error( $term ) ) {
        return 0;
    }

    $term_id = 0;
    if ( is_array( $term ) && isset( $term['term_id'] ) ) {
        $term_id = absint( $term['term_id'] );
    } elseif ( is_int( $term ) || ctype_digit( (string) $term ) ) {
        $term_id = absint( $term );
    }

    if ( $term_id ) {
        update_term_meta( $term_id, 'pax_size', 1 );
    }

    return $term_id;
}
