<?php
defined( 'ABSPATH' ) || exit;

final class MADC_Importer {
    public static function data( $name, $language = 'ar' ) {
        return json_decode( file_get_contents( MADC_PATH . 'data/' . ( 'en' === $language ? 'en/' : '' ) . $name . '.json' ), true );
    }
    public static function items( $kind, $quantity, $language = 'ar' ) {
        if ( 'posts' === $kind ) {
            $presets = self::data( 'article-presets', $language );
            $ids = $presets['options'][ 24 === $quantity ? 1 : 0 ]['article_ids'];
            return array_values( array_filter( self::data( 'articles', $language ), static function ( $a ) use ( $ids ) { return in_array( $a['id'], $ids, true ); } ) );
        }
        $products = self::data( 'products', $language );
        usort( $products, static function ( $a, $b ) { return (int) ( 'grouped' === $a['type'] ) <=> (int) ( 'grouped' === $b['type'] ); } );
        return $products;
    }
    private static function existing( $key, $type ) {
        $ids = get_posts( array( 'post_type' => $type, 'post_status' => array( 'publish', 'draft', 'pending', 'private', 'future', 'trash', 'inherit' ), 'meta_key' => '_madc_key', 'meta_value' => $key, 'fields' => 'ids', 'posts_per_page' => 1, 'suppress_filters' => false ) ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Ownership lookup runs only during an explicit admin import/cleanup; retaining metadata lookup also finds legacy imports and avoids duplicate content.
        return $ids ? (int) $ids[0] : 0;
    }
    private static function checked( $result ) {
        if ( is_wp_error( $result ) ) { throw new RuntimeException( esc_html( $result->get_error_message() ) ); }
        return $result;
    }
    private static function terms( $ids, $taxonomy, $language ) {
        $data = self::data( 'taxonomies', $language );
        $out = array();
        foreach ( array_merge( $data['categories'], $data['tags'] ) as $term ) {
            if ( ! in_array( $term['id'], $ids, true ) ) { continue; }
            $found = term_exists( $term['slug'], $taxonomy );
            if ( ! $found ) {
                $found = self::checked( wp_insert_term( $term['name'], $taxonomy, array( 'slug' => $term['slug'], 'description' => $term['description'] ) ) );
                update_term_meta( (int) $found['term_id'], '_madc_created', 1 );
            }
            $out[] = (int) ( is_array( $found ) ? $found['term_id'] : $found );
        }
        return $out;
    }
    private static function media( $path, $alt, $parent, $language ) {
        $key = ( 'en' === $language ? 'en:' : '' ) . 'media:' . basename( $path );
        $id = self::existing( $key, 'attachment' );
        if ( $id && is_file( (string) get_attached_file( $id ) ) ) { return $id; }
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';
        $source = MADC_PATH . 'data/images/' . basename( $path );
        if ( ! is_file( $source ) ) { throw new RuntimeException( esc_html__( 'A bundled image is missing.', 'majed-arabic-demo-content' ) ); }
        $upload = wp_upload_bits( 'madc-' . basename( $path ), null, file_get_contents( $source ) );
        if ( $upload['error'] ) { throw new RuntimeException( esc_html( $upload['error'] ) ); }
        $id = wp_insert_attachment( array( 'post_mime_type' => 'image/webp', 'post_title' => $alt, 'post_status' => 'inherit', 'meta_input' => array( '_madc_key' => $key, '_wp_attachment_image_alt' => $alt ) ), $upload['file'], $parent, true );
        if ( is_wp_error( $id ) ) { wp_delete_file( $upload['file'] ); self::checked( $id ); }
        $metadata = wp_generate_attachment_metadata( $id, $upload['file'] );
        if ( $metadata ) { wp_update_attachment_metadata( $id, $metadata ); }
        return $id;
    }
    private static function download( $key ) {
        $saved = get_option( 'madc_download_' . $key );
        if ( $saved && is_file( $saved['file'] ) ) { return $saved['url']; }
        $source = MADC_PATH . 'data/downloads/' . basename( $key ) . '.pdf';
        if ( ! is_file( $source ) ) { throw new RuntimeException( esc_html__( 'A bundled download is missing.', 'majed-arabic-demo-content' ) ); }
        $upload = wp_upload_bits( 'madc-' . $key . '.pdf', null, file_get_contents( $source ) );
        if ( $upload['error'] ) { throw new RuntimeException( esc_html( $upload['error'] ) ); }
        update_option( 'madc_download_' . $key, $upload, false );
        return $upload['url'];
    }
    public static function run( $kind, $item, $status, $refresh = false ) {
        $language = isset( $item['language'] ) && 'en' === $item['language'] ? 'en' : 'ar';
        $type = 'posts' === $kind ? 'post' : 'product';
        $id = self::existing( $item['id'], $type );
        if ( $id && 'trash' === get_post_status( $id ) ) { return 'skipped'; }
        $updating = $id && 'post' === $type && $refresh;
        if ( $id && get_post_meta( $id, '_madc_complete', true ) && ! $updating ) { return 'skipped'; }
        if ( $id && ! current_user_can( 'edit_post', $id ) ) { throw new RuntimeException( esc_html__( 'You cannot edit this imported item.', 'majed-arabic-demo-content' ) ); }
        if ( 'post' === $type ) {
            if ( ! $id ) {
                $id = self::checked( wp_insert_post( array( 'post_type' => 'post', 'post_status' => 'draft', 'post_title' => $item['title'], 'post_name' => $item['slug'], 'post_content' => wp_kses_post( $item['content_html'] ), 'post_excerpt' => $item['excerpt'], 'meta_input' => array( '_madc_key' => $item['id'] ) ), true ) );
            }
            if ( $updating ) {
                self::checked( wp_update_post( array( 'ID' => $id, 'post_content' => wp_kses_post( $item['content_html'] ), 'post_excerpt' => $item['excerpt'] ), true ) );
            }
            $image_id = self::media( $item['image_path'], $item['image_text']['alt'], $id, $language );
            set_post_thumbnail( $id, $image_id );
            if ( (int) get_post_thumbnail_id( $id ) !== (int) $image_id ) { throw new RuntimeException( esc_html__( 'The featured image could not be assigned.', 'majed-arabic-demo-content' ) ); }
            update_post_meta( $id, '_madc_content_version', '1.2.0' );
            if ( ! $updating ) {
            self::checked( wp_set_object_terms( $id, self::terms( $item['category_ids'], 'category', $language ), 'category' ) );
            self::checked( wp_set_object_terms( $id, self::terms( $item['tag_ids'], 'post_tag', $language ), 'post_tag' ) );
            self::checked( wp_update_post( array( 'ID' => $id, 'post_status' => $status ), true ) );
            }
        } else {
            $classes = array( 'simple' => 'WC_Product_Simple', 'variable' => 'WC_Product_Variable', 'grouped' => 'WC_Product_Grouped' );
            $class = $classes[ $item['type'] ];
            $p = $id ? wc_get_product( $id ) : new $class();
            if ( ! $id ) {
                $p->set_name( $item['name'] );
                $p->set_slug( $item['slug'] );
                $p->set_status( 'draft' );
                $p->update_meta_data( '_madc_key', $item['id'] );
                $id = $p->save();
            }
            $p->set_description( wpautop( $item['description'] ) . ( empty( $item['features'] ) ? '' : '<ul><li>' . implode( '</li><li>', array_map( 'esc_html', $item['features'] ) ) . '</li></ul>' ) . ( empty( $item['image_disclosure'] ) ? '' : wpautop( $item['image_disclosure'] ) ) );
            $p->set_short_description( $item['short_description'] );
            $p->set_sku( 'MADC-' . strtoupper( $item['id'] ) . '-' . $id );
            $p->set_virtual( $item['virtual'] );
            $p->set_downloadable( $item['downloadable'] );
            $p->set_category_ids( self::terms( $item['category_ids'], 'product_cat', $language ) );
            $p->set_tag_ids( self::terms( $item['tag_ids'], 'product_tag', $language ) );
            if ( isset( $item['regular_price'] ) ) { $p->set_regular_price( (string) $item['regular_price'] ); }
            if ( isset( $item['stock_quantity'] ) ) {
                $p->set_manage_stock( true ); $p->set_stock_quantity( $item['stock_quantity'] );
                $p->set_stock_status( $item['stock_quantity'] > 0 ? 'instock' : 'outofstock' );
            }
            $p->set_image_id( self::media( $item['image_path'], $item['image_text']['alt'], $id, $language ) );
            $gallery = array();
            foreach ( $item['gallery_image_paths'] as $path ) { $gallery[] = self::media( $path, $item['name'], $id, $language ); }
            $p->set_gallery_image_ids( $gallery );
            if ( $item['downloadable'] ) {
                $d = new WC_Product_Download(); $d->set_id( $item['download_asset_id'] ); $d->set_name( $item['file_label'] ); $d->set_file( self::download( $item['download_asset_id'] ) );
                $p->set_downloads( array( $d ) ); $p->set_download_limit( $item['download_limit'] ); $p->set_download_expiry( $item['download_expiry_days'] );
            }
            if ( 'grouped' === $item['type'] ) {
                $children = array();
                foreach ( $item['child_product_ids'] as $child ) {
                    $child_id = self::existing( $child, 'product' );
                    if ( ! $child_id || 'trash' === get_post_status( $child_id ) ) { throw new RuntimeException( esc_html__( 'A grouped product needs its child products. Restore any trashed demo products and retry.', 'majed-arabic-demo-content' ) ); }
                    $children[] = $child_id;
                }
                $p->set_children( $children );
            }
            if ( 'variable' === $item['type'] ) {
                $attrs = array();
                foreach ( $item['attributes'] as $a ) {
                    $attr = new WC_Product_Attribute(); $attr->set_name( $a['name'] ); $attr->set_options( $a['options'] ); $attr->set_visible( true ); $attr->set_variation( true ); $attrs[] = $attr;
                }
                $p->set_attributes( $attrs ); $p->set_default_attributes( $item['default_attributes'] ); $p->save();
                foreach ( $item['variations'] as $v ) {
                    $vid = self::existing( $v['id'], 'product_variation' );
                    $variation = $vid ? new WC_Product_Variation( $vid ) : new WC_Product_Variation();
                    $variation->set_parent_id( $id );
                    $variation_attributes = array();
                    foreach ( $v['attributes'] as $name => $value ) { $variation_attributes[ sanitize_title( $name ) ] = $value; }
                    $variation->set_attributes( $variation_attributes );
                    $variation->set_regular_price( (string) $v['regular_price'] );
                    $variation->set_manage_stock( true ); $variation->set_stock_quantity( $v['stock_quantity'] );
                    $variation->set_stock_status( $v['stock_quantity'] > 0 ? 'instock' : 'outofstock' );
                    $variation->set_description( $v['description'] ); $variation->set_status( 'publish' );
                    $variation->set_sku( 'MADC-' . strtoupper( $v['id'] ) . '-' . $id );
                    $variation->set_image_id( self::media( $v['image_path'], $v['image_alt'], $id, $language ) );
                    $variation->update_meta_data( '_madc_key', $v['id'] ); $variation->save();
                }
                WC_Product_Variable::sync( $id );
            }
            $p->set_status( $status ); $p->save();
            if ( 'variable' === $item['type'] ) { WC_Product_Variable::sync( $id ); }
        }
        update_post_meta( $id, '_madc_complete', 1 );
        return $updating ? 'updated' : 'created';
    }
}
