<?php
/**
 * One Click Demo Import (OCDI) integration.
 *
 * Lets a buyer reproduce the showcased layout in one click using the free
 * "One Click Demo Import" plugin (proteusthemes/one-click-demo-import).
 * The demo files live in /demo/ (content.xml + customizer.dat) and are bundled
 * with the theme. No premium plugin is required.
 *
 * @package    Odysseo
 * @author     Chandrabhan Shekhawat
 * @company    Gigai Kripa Services
 * @link       https://gigaikripaservices.com/
 * @copyright  Copyright (c) 2026, Gigai Kripa Services
 */

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

/**
 * Register the bundled demo with One Click Demo Import.
 */
function odysseo_ocdi_import_files() {
    return array(
        array(
            'import_file_name'             => __( 'Odysseo — Full Demo', 'odysseo-core' ),
            'local_import_file'            => ODYSSEO_CORE_DIR . 'demo/content.xml',
            'local_import_customizer_file' => ODYSSEO_CORE_DIR . 'demo/customizer.dat',
            'import_preview_image_url'     => trailingslashit( get_template_directory_uri() ) . 'screenshot.jpg',
            'preview_url'                  => home_url( '/' ),
            'import_notice'                => __( 'Imports the demo destinations, tour packages, fleet, testimonials, gallery, sample blog posts, pages and Customizer settings. Best run on a fresh install — existing theme demo content is replaced to avoid duplicates.', 'odysseo-core' ),
        ),
    );
}
add_filter( 'ocdi/import_files', 'odysseo_ocdi_import_files' );
add_filter( 'pt-ocdi/import_files', 'odysseo_ocdi_import_files' ); // older OCDI hook prefix (back-compat)

/**
 * Before importing: clear the auto-seeded demo content so an import doesn't
 * create duplicates of items the theme already seeded on activation.
 */
function odysseo_ocdi_before_import() {
    $types = array( 'fleet', 'tour_package', 'destination', 'testimonial', 'gallery_item', 'post' );
    foreach ( $types as $type ) {
        $ids = get_posts( array(
            'post_type'      => $type,
            'posts_per_page' => -1,
            'post_status'    => 'any',
            'fields'         => 'ids',
        ) );
        foreach ( $ids as $id ) {
            wp_delete_post( $id, true );
        }
    }
}
add_action( 'ocdi/before_content_import_execution', 'odysseo_ocdi_before_import' );
add_action( 'pt-ocdi/before_content_import', 'odysseo_ocdi_before_import' );

/**
 * After importing: set the static front page / blog page, build the primary
 * menu and flush rewrite rules so permalinks for the CPTs work immediately.
 *
 * @param array $selected_import The import the user chose (unused).
 */
function odysseo_ocdi_after_import( $selected_import ) {
    // The setup nudge is no longer needed once the demo is imported.
    update_option( 'odysseo_welcome_dismissed', 1 );

    // The WXR importer rewrites URLs in post content but not in post meta, so the
    // demo image URLs stay on demo.example.com. Point them at this site.
    global $wpdb;
    $host = wp_parse_url( home_url(), PHP_URL_HOST );
    if ( $host ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time bulk URL rewrite during demo import; prepared statement, not cacheable.
        $wpdb->query( $wpdb->prepare(
            "UPDATE {$wpdb->postmeta} SET meta_value = REPLACE( meta_value, %s, %s ) WHERE meta_value LIKE %s",
            'demo.example.com',
            $host,
            '%demo.example.com%'
        ) );
    }

    // Static front page (Home) + posts page (Blogs).
    $front = get_page_by_path( 'home' );
    $blog  = get_page_by_path( 'blogs' );
    if ( $front ) {
        update_option( 'show_on_front', 'page' );
        update_option( 'page_on_front', $front->ID );
    }
    if ( $blog ) {
        update_option( 'page_for_posts', $blog->ID );
    }

    // Build a primary menu pointing at the key pages / archives.
    $menu_name = __( 'Primary Menu', 'odysseo-core' );
    $menu      = wp_get_nav_menu_object( $menu_name );
    if ( ! $menu ) {
        $menu_id = wp_create_nav_menu( $menu_name );
        if ( ! is_wp_error( $menu_id ) ) {
            $items = array(
                array( 'title' => __( 'Home', 'odysseo-core' ),          'url' => home_url( '/' ) ),
                array( 'title' => __( 'About Us', 'odysseo-core' ),      'url' => home_url( '/about/' ) ),
                array( 'title' => __( 'Destinations', 'odysseo-core' ),  'url' => get_post_type_archive_link( 'destination' ) ),
                array( 'title' => __( 'Tour Packages', 'odysseo-core' ), 'url' => get_post_type_archive_link( 'tour_package' ) ),
                array( 'title' => __( 'Our Fleets', 'odysseo-core' ),    'url' => home_url( '/fleets/' ) ),
                array( 'title' => __( 'Gallery', 'odysseo-core' ),       'url' => home_url( '/gallery/' ) ),
                array( 'title' => __( 'Blogs', 'odysseo-core' ),         'url' => home_url( '/blogs/' ) ),
                array( 'title' => __( 'Contact', 'odysseo-core' ),       'url' => home_url( '/contact/' ) ),
            );
            foreach ( $items as $item ) {
                if ( empty( $item['url'] ) ) continue;
                wp_update_nav_menu_item( $menu_id, 0, array(
                    'menu-item-title'   => $item['title'],
                    'menu-item-url'     => $item['url'],
                    'menu-item-status'  => 'publish',
                    'menu-item-type'    => 'custom',
                ) );
            }
            $locations = get_theme_mod( 'nav_menu_locations', array() );
            $locations['primary'] = $menu_id;
            set_theme_mod( 'nav_menu_locations', $locations );
        }
    }

    // Import the bundled demo photos and set them as featured images.
    odysseo_demo_assign_images();

    flush_rewrite_rules();
}
add_action( 'ocdi/after_import', 'odysseo_ocdi_after_import' );
add_action( 'pt-ocdi/after_import', 'odysseo_ocdi_after_import' );

/**
 * Side-loads the bundled demo photos (demo/images/) into the media library and
 * assigns them as featured images on the imported demo posts, matched by slug.
 *
 * The WXR import bundles no attachments (to keep the file small and avoid
 * external downloads), so featured images are restored here from photos that
 * ship inside the plugin. Idempotent: an image already imported is reused rather
 * than duplicated.
 */
function odysseo_demo_assign_images() {
    if ( ! function_exists( 'media_handle_sideload' ) ) {
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';
    }

    // post type => ( post slug => bundled image filename ). Packages reuse the
    // scenic photos; fleet keeps the theme's placeholder graphics.
    $map = array(
        'destination'  => array(
            'harbour-city' => 'od_harbour.jpg',
            'azure-bay'    => 'od_azure.jpg',
            'pine-heights' => 'od_pine.jpg',
            'valley-view'  => 'od_valley.jpg',
        ),
        'gallery_item' => array(
            'desert-dunes'     => 'g7.jpg',
            'coastal-lagoon'   => 'g1.jpg',
            'alpine-lake'      => 'g3.jpg',
            'old-town-streets' => 'g5.jpg',
            'city-skyline'     => 'g4.jpg',
            'harbour-at-dusk'  => 'g8.jpg',
            'mountain-summit'  => 'g2.jpg',
            'local-festival'   => 'g6.jpg',
        ),
        'tour_package' => array(
            'classic-city-break' => 'g4.jpg',
            'coastal-escape'     => 'g1.jpg',
            'mountain-adventure' => 'g2.jpg',
            'grand-tour'         => 'od_harbour.jpg',
        ),
        'testimonial'  => array(
            'jane-d' => 'girl1.jpg',
        ),
    );

    $cache = array(); // filename => attachment ID (dedupe reused photos).
    foreach ( $map as $post_type => $slugs ) {
        foreach ( $slugs as $slug => $file ) {
            $post = get_page_by_path( $slug, OBJECT, $post_type );
            if ( ! $post ) {
                continue;
            }
            $att_id = odysseo_demo_sideload_image( $file, $post->ID, $cache );
            if ( $att_id ) {
                set_post_thumbnail( $post->ID, $att_id );
            }
        }
    }
}

/**
 * Side-load one bundled image into the media library, reusing it if already
 * imported. Returns the attachment ID, or 0 on failure.
 *
 * @param string $file     Filename inside demo/images/.
 * @param int    $parent   Post the attachment is attached to.
 * @param array  $cache    Reference cache of filename => attachment ID.
 * @return int
 */
function odysseo_demo_sideload_image( $file, $parent, &$cache ) {
    if ( isset( $cache[ $file ] ) ) {
        return $cache[ $file ];
    }

    // Reuse an existing import (keeps re-imports from duplicating media).
    $existing = get_posts( array(
        'post_type'   => 'attachment',
        'numberposts' => 1,
        'fields'      => 'ids',
        'meta_key'    => '_odysseo_demo_src', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
        'meta_value'  => $file,               // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
    ) );
    if ( $existing ) {
        $cache[ $file ] = $existing[0];
        return $existing[0];
    }

    $path = ODYSSEO_CORE_DIR . 'demo/images/' . $file;
    if ( ! file_exists( $path ) ) {
        return 0;
    }

    $tmp = wp_tempnam( $file );
    if ( ! $tmp ) {
        return 0;
    }
    copy( $path, $tmp );

    $att_id = media_handle_sideload( array( 'name' => $file, 'tmp_name' => $tmp ), (int) $parent );
    if ( is_wp_error( $att_id ) ) {
        if ( file_exists( $tmp ) ) {
            wp_delete_file( $tmp );
        }
        return 0;
    }

    update_post_meta( $att_id, '_odysseo_demo_src', $file );
    $cache[ $file ] = $att_id;
    return $att_id;
}
