<?php
defined( 'ABSPATH' ) || exit;
final class MADC_Admin {
    public function __construct() {
        add_action( 'admin_menu', array( $this, 'menu' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'assets' ) );
        add_action( 'rest_api_init', array( $this, 'routes' ) );
    }
    public function menu() {
        add_menu_page( __( 'Arabic Demo Content', 'majed-arabic-demo-content' ), __( 'Arabic Demo Content', 'majed-arabic-demo-content' ), 'manage_options', 'majed-arabic-demo-content', array( $this, 'page' ), 'dashicons-welcome-write-blog', 59 );
    }
    public function assets( $hook ) {
        if ( 'toplevel_page_majed-arabic-demo-content' !== $hook ) { return; }
        wp_enqueue_style( 'madc-admin', MADC_URL . 'assets/admin.css', array(), MADC_VERSION );
        wp_enqueue_script( 'madc-admin', MADC_URL . 'assets/admin.js', array(), MADC_VERSION, true );
        wp_localize_script( 'madc-admin', 'madc', array(
            'cleanupPreviewUrl' => rest_url( 'madc/v1/cleanup/preview' ), 'cleanupUrl' => rest_url( 'madc/v1/cleanup' ),
            'updated' => __( 'Updated', 'majed-arabic-demo-content' ),
            'cleanupWorking' => __( 'Deleting demo content… Keep this page open.', 'majed-arabic-demo-content' ),
            'cleanupDone' => __( 'Cleanup complete.', 'majed-arabic-demo-content' ),
            'cleanupFailed' => __( 'Cleanup stopped. Retry to continue.', 'majed-arabic-demo-content' ),
            'deleted' => __( 'Deleted', 'majed-arabic-demo-content' ), 'kept' => __( 'Kept for safety or permissions', 'majed-arabic-demo-content' ),
            'cleanupConfirm' => __( 'Permanently delete the following imported demo items in both languages? This includes edits made to demo posts and products. Shared media and used categories are kept. This cannot be undone.', 'majed-arabic-demo-content' ),
            'nothing' => __( 'There is no tracked demo content to delete.', 'majed-arabic-demo-content' ),
            'cleanupLabels' => array( 'post' => __( 'Articles', 'majed-arabic-demo-content' ), 'product' => __( 'Products', 'majed-arabic-demo-content' ), 'product_variation' => __( 'Variations', 'majed-arabic-demo-content' ), 'attachment' => __( 'Images', 'majed-arabic-demo-content' ), 'term' => __( 'Categories and tags', 'majed-arabic-demo-content' ), 'download' => __( 'PDF files', 'majed-arabic-demo-content' ) ),
            'url' => rest_url( 'madc/v1/import' ), 'nonce' => wp_create_nonce( 'wp_rest' ),
            'working' => __( 'Importing… Keep this page open.', 'majed-arabic-demo-content' ),
            'done' => __( 'Import complete.', 'majed-arabic-demo-content' ),
            'failed' => __( 'Import stopped. Retry to continue without duplicates.', 'majed-arabic-demo-content' ),
            'created' => __( 'Created', 'majed-arabic-demo-content' ), 'skipped' => __( 'Already imported', 'majed-arabic-demo-content' ),
        ) );
    }
    public function routes() {
        $permission = static function () { return current_user_can( 'manage_options' ) && current_user_can( 'upload_files' ); };
        register_rest_route( 'madc/v1', '/cleanup/preview', array( 'methods' => 'POST', 'callback' => array( $this, 'cleanup' ), 'permission_callback' => $permission ) );
        register_rest_route( 'madc/v1', '/cleanup', array( 'methods' => 'POST', 'callback' => array( $this, 'cleanup' ), 'permission_callback' => $permission, 'args' => array(
            'token' => array( 'required' => true, 'type' => 'string', 'minLength' => 40, 'maxLength' => 40 ),
            'confirm' => array( 'required' => true, 'type' => 'boolean', 'enum' => array( true ) ),
        ) ) );

        register_rest_route( 'madc/v1', '/import', array( 'methods' => 'POST', 'callback' => array( $this, 'step' ), 'permission_callback' => static function () { return current_user_can( 'manage_options' ); }, 'args' => array(
            'kind' => array( 'required' => true, 'type' => 'string', 'enum' => array( 'posts', 'products' ) ),
            'language' => array( 'type' => 'string', 'enum' => array( 'ar', 'en' ), 'default' => 'ar' ),
            'refresh' => array( 'type' => 'boolean', 'default' => false ),
            'quantity' => array( 'required' => true, 'type' => 'integer', 'enum' => array( 12, 24 ) ),
            'index' => array( 'required' => true, 'type' => 'integer', 'minimum' => 0, 'maximum' => 27 ),
            'status' => array( 'required' => true, 'type' => 'string', 'enum' => array( 'draft', 'publish' ) ),
        ) ) );
    }
    public function cleanup( $request ) {
        if ( ! add_option( 'madc_import_lock', time(), '', false ) ) {
            if ( (int) get_option( 'madc_import_lock' ) < time() - 600 ) { delete_option( 'madc_import_lock' ); }
            return new WP_Error( 'madc_busy', __( 'Another import is running. Please retry shortly.', 'majed-arabic-demo-content' ), array( 'status' => 409 ) );
        }
        try {
            return rest_ensure_response( '/madc/v1/cleanup/preview' === $request->get_route() ? MADC_Cleanup::preview() : MADC_Cleanup::step( $request['token'] ) );
        } catch ( Throwable $e ) {
            self::report_failure( 'cleanup' );
            return new WP_Error( 'madc_cleanup_failed', __( 'Cleanup could not finish. Check file permissions and ensure WooCommerce is active, then retry.', 'majed-arabic-demo-content' ), array( 'status' => 500 ) );
        } finally { delete_option( 'madc_import_lock' ); }
    }
    public function step( $request ) {
        $kind = $request['kind']; $status = $request['status'];
        if ( MADC_Cleanup::active() ) { return new WP_Error( 'madc_cleanup_active', __( 'Finish the current cleanup before importing content.', 'majed-arabic-demo-content' ), array( 'status' => 409 ) ); }
        $object = get_post_type_object( 'posts' === $kind ? 'post' : 'product' );
        if ( ! $object || ! current_user_can( 'upload_files' ) || ! current_user_can( $object->cap->create_posts ) || ! current_user_can( $object->cap->edit_posts ) || ( 'publish' === $status && ! current_user_can( $object->cap->publish_posts ) ) || ( 'products' === $kind && ( ! class_exists( 'WooCommerce' ) || ! current_user_can( 'upload_files' ) ) ) ) {
            return new WP_Error( 'madc_permission', __( 'You cannot import this content. Products require WooCommerce and the appropriate permissions.', 'majed-arabic-demo-content' ), array( 'status' => 403 ) );
        }
        $items = MADC_Importer::items( $kind, (int) $request['quantity'], $request['language'] );
        $index = (int) $request['index'];
        if ( ! isset( $items[ $index ] ) ) { return new WP_Error( 'madc_index', __( 'Invalid import item.', 'majed-arabic-demo-content' ), array( 'status' => 400 ) ); }
        // An atomic option prevents concurrent requests from importing the same library item.
        if ( ! add_option( 'madc_import_lock', time(), '', false ) ) {
            if ( (int) get_option( 'madc_import_lock' ) < time() - 600 ) { delete_option( 'madc_import_lock' ); }
            return new WP_Error( 'madc_busy', __( 'Another import is running. Please retry shortly.', 'majed-arabic-demo-content' ), array( 'status' => 409 ) );
        }
        try {
            $result = MADC_Importer::run( $kind, $items[ $index ], $status, (bool) $request['refresh'] );
            return rest_ensure_response( array( 'result' => $result, 'total' => count( $items ), 'title' => $items[ $index ][ 'posts' === $kind ? 'title' : 'name' ] ) );
        } catch ( Throwable $e ) {
            self::report_failure( 'import' );
            return new WP_Error( 'madc_import', __( 'Import failed. Check upload permissions, available storage, and any trashed demo products, then retry.', 'majed-arabic-demo-content' ), array( 'status' => 500 ) );
        } finally { delete_option( 'madc_import_lock' ); }
    }
    private static function report_failure( $operation ) {
        if ( ! defined( 'WP_DEBUG_LOG' ) || ! WP_DEBUG_LOG || ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) { return; }
        // Only fixed operation names are logged; exception messages can contain site paths or private data.
        if ( function_exists( 'wc_get_logger' ) ) {
            wc_get_logger()->error( 'Demo content operation failed: ' . $operation, array( 'source' => 'majed-arabic-demo-content' ) );
        }
        // Article-only sites can attach their own diagnostic logger without a WooCommerce dependency.
        do_action( 'madc_operation_failed', $operation );
    }
    public function page() {
        if ( ! current_user_can( 'manage_options' ) ) { return; }
        ?>
        <div class="wrap madc-admin" dir="<?php echo is_rtl() ? 'rtl' : 'ltr'; ?>"><div class="madc-shell">
        <header class="madc-header"><span class="madc-mark dashicons dashicons-welcome-write-blog" aria-hidden="true"></span><div><span class="madc-eyebrow">Majed <span class="madc-badge">v<?php echo esc_html( MADC_VERSION ); ?></span></span><h1><?php esc_html_e( 'Arabic Demo Content', 'majed-arabic-demo-content' ); ?></h1><p><?php esc_html_e( 'Build a realistic demo with ready-made Arabic or English content.', 'majed-arabic-demo-content' ); ?></p></div></header><hr class="wp-header-end">
        <div class="madc-summary"><span><?php esc_html_e( '24 articles per language', 'majed-arabic-demo-content' ); ?></span><span><?php esc_html_e( '28 products per language', 'majed-arabic-demo-content' ); ?></span><span><?php esc_html_e( '60 product images', 'majed-arabic-demo-content' ); ?></span><span><?php esc_html_e( 'Works offline', 'majed-arabic-demo-content' ); ?></span></div>
        <form id="madc-form"><fieldset id="madc-controls"><legend class="screen-reader-text"><?php esc_html_e( 'Import settings', 'majed-arabic-demo-content' ); ?></legend>
        <section class="madc-card"><h2><label for="madc-language"><?php esc_html_e( 'Demo content language', 'majed-arabic-demo-content' ); ?></label></h2><select id="madc-language" name="language"><option value="ar"><?php esc_html_e( 'Arabic', 'majed-arabic-demo-content' ); ?></option><option value="en"><?php esc_html_e( 'English', 'majed-arabic-demo-content' ); ?></option></select><p class="madc-muted"><?php esc_html_e( 'Choose the language of imported content. The admin interface keeps your WordPress user language.', 'majed-arabic-demo-content' ); ?></p></section>
        <div class="madc-grid"><label class="madc-card madc-choice"><input type="radio" name="kind" value="posts" checked><span class="dashicons dashicons-admin-post" aria-hidden="true"></span><strong><?php esc_html_e( 'Articles', 'majed-arabic-demo-content' ); ?></strong><span><?php esc_html_e( 'Expanded articles in your selected language with featured images, categories, tags, and excerpts. Images come from the bundled product library.', 'majed-arabic-demo-content' ); ?></span></label>
        <label class="madc-card madc-choice"><input type="radio" name="kind" value="products" <?php disabled( ! class_exists( 'WooCommerce' ) ); ?>><span class="dashicons dashicons-cart" aria-hidden="true"></span><strong><?php esc_html_e( 'WooCommerce products', 'majed-arabic-demo-content' ); ?></strong><span><?php esc_html_e( 'Simple, variable, grouped, digital, and service products with dedicated images and PDF downloads.', 'majed-arabic-demo-content' ); ?></span><?php if ( ! class_exists( 'WooCommerce' ) ) : ?><small><?php esc_html_e( 'Activate WooCommerce to import products.', 'majed-arabic-demo-content' ); ?></small><?php endif; ?></label></div>
        <section class="madc-card"><h2><?php esc_html_e( 'Customize your import', 'majed-arabic-demo-content' ); ?></h2><div class="madc-fields"><div id="madc-quantity"><label for="quantity"><?php esc_html_e( 'Number of articles', 'majed-arabic-demo-content' ); ?></label><select id="quantity" name="quantity"><option value="12">12</option><option value="24">24</option></select></div><div><label for="madc-status"><?php esc_html_e( 'Content status', 'majed-arabic-demo-content' ); ?></label><select name="status" id="madc-status"><option value="draft"><?php esc_html_e( 'Draft — review before publishing', 'majed-arabic-demo-content' ); ?></option><option value="publish"><?php esc_html_e( 'Published — visible immediately', 'majed-arabic-demo-content' ); ?></option></select></div></div>
        <p id="madc-refresh"><label><input type="checkbox" name="refresh" value="1"> <?php esc_html_e( 'Replace text and featured images of previously imported articles. Existing titles and publication status are preserved.', 'majed-arabic-demo-content' ); ?></label></p>
        <p class="madc-muted"><?php esc_html_e( 'Arabic and English content can coexist. Existing imports in the selected language are skipped unless article updates are selected. Trashed items are skipped. Prices use your store currency.', 'majed-arabic-demo-content' ); ?></p>
        <button type="submit" class="button button-primary"><?php esc_html_e( 'Import demo content', 'majed-arabic-demo-content' ); ?></button></section></fieldset></form>
        <section class="madc-card" id="madc-progress-panel" hidden><h2><?php esc_html_e( 'Import progress', 'majed-arabic-demo-content' ); ?></h2><progress id="madc-progress" max="100" value="0" aria-label="<?php esc_attr_e( 'Import progress', 'majed-arabic-demo-content' ); ?>"></progress><p id="madc-result" role="status" aria-live="polite"></p><p id="madc-item" dir="auto"></p></section>
        <section class="madc-card madc-cleanup" aria-labelledby="madc-cleanup-title"><h2 id="madc-cleanup-title"><?php esc_html_e( 'Finished building your demo?', 'majed-arabic-demo-content' ); ?></h2><p><?php esc_html_e( 'Delete all tracked demo articles, products, variations, images, PDFs, and unused categories in both languages. Deletion is permanent, including edits you made to these demo items.', 'majed-arabic-demo-content' ); ?></p><p class="madc-muted"><?php esc_html_e( 'Other content is kept. Media referenced by remaining content and categories still in use are retained. Categories from versions before 1.1.0 are retained because their original ownership was not recorded.', 'majed-arabic-demo-content' ); ?></p><button type="button" id="madc-cleanup-button" class="button madc-danger"><?php esc_html_e( 'Delete imported demo content', 'majed-arabic-demo-content' ); ?></button><div id="madc-cleanup-progress" hidden><progress id="madc-cleanup-bar" value="0" max="100" aria-label="<?php esc_attr_e( 'Cleanup progress', 'majed-arabic-demo-content' ); ?>"></progress><p id="madc-cleanup-result" role="status" aria-live="polite"></p></div></section>
        <footer class="madc-muted"><?php esc_html_e( 'By Majed Bannani. Imported content and media remain available when the plugin is deactivated or removed.', 'majed-arabic-demo-content' ); ?></footer>
        <aside class="madc-support-card" aria-labelledby="madc-support-title"><div class="madc-support-copy"><h2 id="madc-support-title"><?php esc_html_e( 'Made with care, sustained by your support', 'majed-arabic-demo-content' ); ?> <span class="madc-support-heart" aria-hidden="true">♥</span></h2><p><?php esc_html_e( 'This plugin is free and grows with the support of its users. If it has helped you manage your site, you can contribute to its continued development and new tools.', 'majed-arabic-demo-content' ); ?></p></div><a class="button madc-support-button" href="https://www.paypal.com/ncp/payment/2C3DDKHKMPMLC" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Support via PayPal', 'majed-arabic-demo-content' ); ?></a></aside></div></div>
        <?php
    }
}
