<?php
if (!defined('ABSPATH')) {exit;}
function drop_print_build_connect_url($user_id, array $overrides = array()) {
    $user_id = absint($user_id);
    if ($user_id === 0) return '';
    $server_login_url = defined('DROP_PRINT_API_URI') ? DROP_PRINT_API_URI . "/authenticate" : '';
    if (empty($server_login_url)) return '';
    $connection_token = wp_create_nonce('drop_print_connect_' . $user_id);
    set_transient('drop_print_connect_token_' . $user_id, $connection_token, HOUR_IN_SECONDS);
    $wp_user = get_userdata($user_id);
    $client_wc_currency = class_exists('WooCommerce') ? get_option('woocommerce_currency') : '';
    $client_user_email = ($wp_user && !empty($wp_user->user_email)) ? $wp_user->user_email : '';
    $query_args = array(
        'connection_token' => $connection_token,
        'client_url' => urlencode(admin_url('admin.php?page=drop-print-settings')),
        'start_mode' => 'register',
        'rest_endpoint' => urlencode(get_rest_url(null, 'drop-print-client/v1/complete-connection')),
        'client_uid' => $user_id,
        'source' => 'drop-print-' . (defined('DROP_PRINT_VERSION') ? DROP_PRINT_VERSION : 'unknown'),
    );
    if (!empty($client_wc_currency)) {
        $query_args['client_pref_currency'] = sanitize_text_field($client_wc_currency);
    }
    if (!empty($client_user_email)) {
        $query_args['client_user_email'] = urlencode($client_user_email);
    }
    foreach ($overrides as $key => $value) {
        if ($value === null || $value === '') continue;
        $query_args[$key] = in_array($key, array('client_url', 'client_user_email'), true)
            ? urlencode($value)
            : sanitize_text_field($value);
    }
    return add_query_arg($query_args, $server_login_url);
}
function drop_print_display_connect_notice() {
    $current_user_id = get_current_user_id();
    if ($current_user_id === 0) return;
    $user_settings = drop_print_get_user_settings($current_user_id);
    if (!empty($user_settings['client_user_connection_id'])) return;
    if (!current_user_can('manage_options')) return;
    $screen = get_current_screen();
    $show_notice = !$screen || in_array($screen->id, array('toplevel_page_drop-print-settings', 'dashboard', 'plugins', 'product'), true);
    if (!$show_notice && 'admin_notices' === current_filter()) return;
    $connect_url = drop_print_build_connect_url($current_user_id);
    if (empty($connect_url)) {
        echo '<div class="notice notice-error"><p>' . esc_html__('Drop Print server connection URL is not configured. Please contact support.', 'drop-print') . '</p></div>';
        return;
    }
    ?>
    <div class="notice notice-warning drop-print-connect-notice">
        <p><strong><?php esc_html_e('Connect to Drop Print to enable print-on-demand products and fulfilment', 'drop-print'); ?></strong></p>
        <p><a href="<?php echo esc_url($connect_url); ?>" class="button button-primary"><?php esc_html_e('Connect Account', 'drop-print'); ?></a></p>
        <?php
        $auth_host = wp_parse_url($connect_url, PHP_URL_HOST);
        ?>
        <?php if ($auth_host) : ?>
        <p class="description"><?php echo esc_html(sprintf( __('You\'ll navigate to %s for authentication. Your browser will automatically return to your Dashboard upon completion.', 'drop-print'), $auth_host)); ?></p>
        <?php endif; ?>
    </div>
    <?php
}
add_action('admin_notices', 'drop_print_display_connect_notice');
function drop_print_register_connection_rest_routes() {
    register_rest_route(
        'drop-print-client/v1',
        '/complete-connection',
        array(
            'methods' => WP_REST_Server::CREATABLE,
            'callback' => 'drop_print_rest_complete_connection_callback',
            'permission_callback' => 'drop_print_rest_connection_permission_callback',
            'args' => array(
                'connection_token' => ['required' => true, 'validate_callback' => function ($param) { return is_string($param) && !empty($param); }, 'sanitize_callback' => 'sanitize_text_field'],
                '_drop_print_server_client_uid' => ['required' => true, 'validate_callback' => function ($param) { return is_numeric($param) && $param > 0; }, 'sanitize_callback' => 'absint'],
                '_drop_print_server_client_id' => ['required' => true, 'validate_callback' => function ($param) { return is_string($param) && !empty($param); }, 'sanitize_callback' => 'sanitize_text_field'],
                '_drop_print_server_public_pem_b64' => ['required' => true, 'validate_callback' => function ($param) { return is_string($param) && !empty($param); }, 'sanitize_callback' => 'sanitize_textarea_field'],
                '_drop_print_server_billing_currency' => ['required' => true, 'validate_callback' => function ($param) { return is_string($param) && !empty($param); }, 'sanitize_callback' => 'sanitize_text_field'],
                '_drop_print_server_auth_username_b64' => ['required' => true, 'validate_callback' => function ($param) { return is_string($param) && !empty($param); }, 'sanitize_callback' => 'sanitize_text_field'],
                '_drop_print_server_auth_password_b64' => ['required' => true, 'validate_callback' => function ($param) { return is_string($param) && !empty($param); }, 'sanitize_callback' => 'sanitize_text_field'],
                '_drop_print_server_pro_status' => ['required' => true, 'validate_callback' => function ($param) { return is_numeric($param) && ($param == 0 || $param == 1); }, 'sanitize_callback' => 'absint'],
                '_drop_print_server_available_media' => ['required' => false, 'type' => 'array', 'validate_callback' => function ($param) { return is_array($param); },],
                '_drop_print_server_username_display' => ['required' => false, 'validate_callback' => function ($param) { return is_string($param) && !empty($param); }, 'sanitize_callback' => 'sanitize_email'],
            ),
        )
    );
}
add_action('rest_api_init', 'drop_print_register_connection_rest_routes');
function drop_print_rest_connection_permission_callback(WP_REST_Request $request) {
    $received_token = $request->get_param('connection_token');
    $client_uid = $request->get_param('_drop_print_server_client_uid');
    if (empty($received_token) || !is_numeric($client_uid) || $client_uid <= 0) {
        return new WP_Error('rest_missing_perm_params', __('Missing parameters required for authentication.', 'drop-print'), array('status' => 400));
    }
    $stored_token_key = 'drop_print_connect_token_' . $client_uid;
    $stored_token = get_transient($stored_token_key);
    if (!$stored_token || !hash_equals($stored_token, $received_token)) {
        return new WP_Error('rest_invalid_token', __('Invalid or expired connection token.', 'drop-print'), array('status' => 403));
    }
    return true;
}
function drop_print_rest_complete_connection_callback(WP_REST_Request $request) {
    $params = $request->get_params();
    $client_uid = absint($params['_drop_print_server_client_uid'] ?? 0);
    if ($client_uid === 0) {
        return new WP_Error('rest_missing_client_uid', __('Client user ID missing or invalid.', 'drop-print'), array('status' => 400));
    }
    $current_user_settings = drop_print_get_user_settings($client_uid);
    $new_connection_data = [];
    $new_connection_data['client_user_connection_id'] = sanitize_text_field($params['_drop_print_server_client_id'] ?? '');
    $new_connection_data['public_key_pem_b64'] = sanitize_textarea_field($params['_drop_print_server_public_pem_b64'] ?? '');
    $new_connection_data['billing_currency'] = sanitize_text_field(strtoupper($params['_drop_print_server_billing_currency'] ?? ''));
    $new_connection_data['auth_username_b64'] = sanitize_text_field($params['_drop_print_server_auth_username_b64'] ?? '');
    $new_connection_data['auth_password_b64'] = sanitize_text_field($params['_drop_print_server_auth_password_b64'] ?? '');
    $new_connection_data['pro_status'] = absint($params['_drop_print_server_pro_status'] ?? 0);
    $raw_available_media = $params['_drop_print_server_available_media'] ?? [];
    $sanitized_available_media = [];
    if (is_array($raw_available_media)) {
        foreach ($raw_available_media as $item) {
            if (is_array($item) && isset($item['id'], $item['name']) && is_string($item['id']) && is_string($item['name'])) {
                $sanitized_available_media[] = ['id' => sanitize_key($item['id']), 'name' => sanitize_text_field($item['name'])];
            }
        }
    }
    $new_connection_data['available_media'] = $sanitized_available_media;
    $new_connection_data['media_last_updated'] = time();
    $new_connection_data['user_display_name'] = sanitize_email($params['_drop_print_server_username_display'] ?? '');
    if (empty($new_connection_data['client_user_connection_id']) || empty($new_connection_data['public_key_pem_b64']) || empty($new_connection_data['billing_currency']) || empty($new_connection_data['auth_username_b64']) || empty($new_connection_data['auth_password_b64'])) {
        return new WP_Error('rest_missing_payload_data', __('Connection confirmation failed: Incomplete data received from server.', 'drop-print'), array('status' => 400));
    }
    $updated_user_settings = array_merge($current_user_settings, $new_connection_data);
    if (update_user_meta($client_uid, 'drop_print_user_settings', $updated_user_settings)) {
        delete_transient('drop_print_connect_token_' . $client_uid);
        set_transient('drop_print_just_connected_' . $client_uid, 1, 5 * MINUTE_IN_SECONDS);
        do_action('drop_print_connected', $client_uid);
        if (function_exists('drop_print_client_refresh_data_and_status')) {
            if (!wp_next_scheduled('drop_print_initial_user_data_sync_hook', array('user_id' => $client_uid))) {
                wp_schedule_single_event(time() + 20, 'drop_print_initial_user_data_sync_hook', array('user_id' => $client_uid));
            }
        }
        return new WP_REST_Response(['success' => true, 'message' => __('Drop Print authentication successful. Connection details saved for your user.', 'drop-print')], 200);
    } else {
        $existing_user_settings_for_compare = get_user_meta($client_uid, 'drop_print_user_settings', true);
        if(!is_array($existing_user_settings_for_compare)) $existing_user_settings_for_compare = [];
        $connection_parts_identical = true;
        foreach ($new_connection_data as $key => $value) {
            if (!isset($existing_user_settings_for_compare[$key]) || $existing_user_settings_for_compare[$key] !== $value) {
                if ($key !== 'media_last_updated') {
                    $connection_parts_identical = false;
                    break;
                }
            }
        }
        if ($connection_parts_identical) {
            delete_transient('drop_print_connect_token_' . $client_uid);
            do_action('drop_print_connected', $client_uid);
            if (function_exists('drop_print_client_refresh_data_and_status')) {
                if (!wp_next_scheduled('drop_print_initial_user_data_sync_hook', array('user_id' => $client_uid))) {
                    wp_schedule_single_event(time() + 25, 'drop_print_initial_user_data_sync_hook', array('user_id' => $client_uid));
                }
            }
            return new WP_REST_Response(['success' => true, 'message' => __('Drop Print connection re-confirmed for your user. Details effectively unchanged.', 'drop-print')], 200);
        } else {
            return new WP_Error('rest_user_meta_save_failed', __('Connection confirmation failed: Could not save connection details for your user.', 'drop-print'), array('status' => 500));
        }
    }
}
function drop_print_display_user_connected_status_notice() {
    $screen = get_current_screen();
    if (!$screen || 'toplevel_page_drop-print-settings' !== $screen->id) return;
    $current_user_id = get_current_user_id();
    if ($current_user_id === 0) return;
    $transient_key = 'drop_print_just_connected_' . $current_user_id;
    if (!get_transient($transient_key)) return;
    delete_transient($transient_key);
    $user_settings = drop_print_get_user_settings($current_user_id);
    if (empty($user_settings['client_user_connection_id'])) return;
    $add_product_url = add_query_arg('drop_print_show_tour', '1', admin_url('post-new.php?post_type=product'));
    ?>
    <div class="notice notice-success is-dismissible">
        <p><strong><?php esc_html_e("You're connected to Drop Print!", 'drop-print'); ?></strong></p>
        <p><?php esc_html_e('Head over to a product to see it in action — tick the Drop Print box, add your artwork, and choose your sizes.', 'drop-print'); ?></p>
        <p>
            <a href="<?php echo esc_url($add_product_url); ?>" class="button button-primary"><?php esc_html_e('Add a Drop Print Product', 'drop-print'); ?></a>
        </p>
    </div>
    <?php
}
add_action('admin_notices', 'drop_print_display_user_connected_status_notice', 11);
if (!defined('DROP_PRINT_PRODUCT_CTA_SNOOZE_HOURS')) {
    define('DROP_PRINT_PRODUCT_CTA_SNOOZE_HOURS', 24);
}
function drop_print_display_product_cta_notice() {
    $current_user_id = get_current_user_id();
    if ($current_user_id === 0) return;
    $screen = get_current_screen();
    if ($screen && 'product' === $screen->id && 'post' === $screen->base) return;
    if (get_transient('drop_print_just_connected_' . $current_user_id)) return;
    $user_settings = drop_print_get_user_settings($current_user_id);
    if (empty($user_settings['client_user_connection_id'])) return;
    if (function_exists('drop_print_has_any_container_file') && drop_print_has_any_container_file()) return;
    $snoozed_at = absint(get_user_meta($current_user_id, 'drop_print_product_cta_snoozed_at', true));
    if ($snoozed_at > 0 && (time() - $snoozed_at) < (DROP_PRINT_PRODUCT_CTA_SNOOZE_HOURS * HOUR_IN_SECONDS)) return;
    $add_product_url = add_query_arg('drop_print_show_tour', '1', admin_url('post-new.php?post_type=product'));
    $nonce = wp_create_nonce('drop_print_snooze_product_cta');
    ?>
    <div class="notice notice-info is-dismissible drop-print-product-cta-notice" data-snooze-nonce="<?php echo esc_attr($nonce); ?>">
        <p><strong><?php esc_html_e('See Drop Print in action', 'drop-print'); ?></strong></p>
        <p><?php esc_html_e('Add or edit a product to start the guided Drop Print walkthrough — tick the Drop Print box, drop in your artwork, and choose your sizes.', 'drop-print'); ?></p>
        <p>
            <a href="<?php echo esc_url($add_product_url); ?>" class="button button-primary"><?php esc_html_e('Add a Drop Print Product', 'drop-print'); ?></a>
        </p>
    </div>
    <script>
    (function($){
        $(function(){
            $(document).on('click', '.drop-print-product-cta-notice .notice-dismiss', function(){
                var $notice = $(this).closest('.drop-print-product-cta-notice');
                $.post(ajaxurl, {
                    action: 'drop_print_snooze_product_cta',
                    nonce: $notice.data('snooze-nonce')
                });
            });
        });
    })(jQuery);
    </script>
    <?php
}
add_action('admin_notices', 'drop_print_display_product_cta_notice');
function drop_print_snooze_product_cta_handler() {
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_key(wp_unslash($_POST['nonce'])), 'drop_print_snooze_product_cta')) {
        wp_send_json_error(array('message' => __('Security check failed.', 'drop-print')), 403);
        return;
    }
    $user_id = get_current_user_id();
    if ($user_id <= 0) {
        wp_send_json_error(array('message' => __('Not logged in.', 'drop-print')), 403);
        return;
    }
    update_user_meta($user_id, 'drop_print_product_cta_snoozed_at', time());
    wp_send_json_success();
}
add_action('wp_ajax_drop_print_snooze_product_cta', 'drop_print_snooze_product_cta_handler');
function drop_print_handle_scheduled_initial_user_sync($user_id = 0) {
    $user_id = absint(is_array($user_id) ? ($user_id['user_id'] ?? 0) : $user_id);
    if ($user_id > 0 && function_exists('drop_print_client_refresh_data_and_status')) {
        drop_print_client_refresh_data_and_status($user_id);
    }
}
add_action('drop_print_initial_user_data_sync_hook', 'drop_print_handle_scheduled_initial_user_sync', 10, 1);
