<?php

class PeepSoGettingstartedajax extends PeepSoAjaxCallback
{
    public function save_step3(PeepSoAjaxResponse $resp)
    {
        if (!PeepSo::is_admin()) {
            $resp->error(__('Access denied.', 'peepso-core'));
            return;
        }

        $header = sanitize_text_field($this->_input->value('header', '', FALSE));
        $callout = sanitize_textarea_field($this->_input->value('callout', '', FALSE));
        $button_text = sanitize_text_field($this->_input->value('button_text', '', FALSE));
        $image_mode = sanitize_key($this->_input->value('image_mode', 'default', FALSE));
        $image_value = esc_url_raw($this->_input->value('image_value', '', FALSE));

        $config = PeepSoConfigSettings::get_instance();
        $config->set_option('site_registration_header', $header);
        $config->set_option('site_registration_callout', $callout);
        $config->set_option('site_registration_buttontext', $button_text);

        $default_image = PeepSo::get_asset('images/landing/register-bg.jpg');
        $image_url = '';
        $image_is_default = FALSE;

        switch ($image_mode) {
            case 'custom':
                if (!strlen($image_value)) {
                    $config->remove_option('landing_page_image');
                    $image_is_default = TRUE;
                    break;
                }

                $config->set_option('landing_page_image', $image_value);
                $image_url = $image_value;
                break;

            case 'preset':
                if (!strlen($image_value)) {
                    $config->remove_option('landing_page_image');
                    $image_is_default = TRUE;
                    break;
                }

                $local_image = $this->get_or_sideload_image($image_value);
                if (is_wp_error($local_image)) {
                    $resp->error($local_image->get_error_message());
                    return;
                }

                $config->set_option('landing_page_image', $local_image);
                $image_url = $local_image;
                break;

            case 'default':
            default:
                $config->remove_option('landing_page_image');
                $image_is_default = TRUE;
                break;
        }

        if ($image_is_default) {
            $image_url = '';
        }

        $resp->set('data', array(
            'header' => $header,
            'callout' => $callout,
            'button_text' => $button_text,
            'image_url' => $image_url,
            'image_is_default' => $image_is_default,
            'default_image' => $default_image,
        ));
        $resp->success(TRUE);
    }

    protected function get_or_sideload_image($source_url)
    {
        $source_url = esc_url_raw($source_url);

        if (!strlen($source_url)) {
            return new WP_Error('peepso_invalid_image', __('Invalid image URL.', 'peepso-core'));
        }

        foreach (array('_peepso_getting_started_source_url', '_source_url') as $meta_key) {
            $existing = get_posts(array(
                'post_type' => 'attachment',
                'post_status' => 'inherit',
                'posts_per_page' => 1,
                'fields' => 'ids',
                'meta_key' => $meta_key,
                'meta_value' => $source_url,
            ));

            if (!empty($existing)) {
                $existing_url = wp_get_attachment_url($existing[0]);
                if ($existing_url) {
                    return $existing_url;
                }
            }
        }

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

        $tmp = download_url($source_url, 30);
        if (is_wp_error($tmp)) {
            return new WP_Error(
                'peepso_sideload_failed',
                __('The selected preset image could not be downloaded. Please pick a different image or upload your own.', 'peepso-core')
            );
        }

        $mime = function_exists('wp_get_image_mime') ? wp_get_image_mime($tmp) : '';
        $extensions = array(
            'image/jpeg' => 'jpg',
            'image/png' => 'png',
            'image/gif' => 'gif',
            'image/webp' => 'webp',
            'image/avif' => 'avif',
        );

        if (!isset($extensions[$mime])) {
            @unlink($tmp);
            return new WP_Error(
                'peepso_invalid_image_type',
                __('The selected preset image is not a supported image format. Please pick a different image or upload your own.', 'peepso-core')
            );
        }

        $file_array = array(
            'name' => 'peepso-landing-' . md5($source_url) . '.' . $extensions[$mime],
            'tmp_name' => $tmp,
        );

        $attachment_id = media_handle_sideload($file_array, 0, __('PeepSo Getting Started landing page image', 'peepso-core'));

        if (is_wp_error($attachment_id)) {
            @unlink($tmp);
            return new WP_Error(
                'peepso_sideload_failed',
                __('The selected preset image could not be downloaded. Please pick a different image or upload your own.', 'peepso-core')
            );
        }

        update_post_meta($attachment_id, '_peepso_getting_started_source_url', $source_url);

        return esc_url_raw(wp_get_attachment_url($attachment_id));
    }
}
