<?php

/**
 * Global settings page for the 3D Product Customizer.
 *
 * Registers the settings page, fields, sanitization, and render callbacks
 * for camera position, background colors, zoom limits, and HDR environment map.
 *
 * @package ProductCustomizer
 */
// Exit if accessed directly.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// admin/plugin-settings.php
function dprcu_mime_types(  $mimes  ) {
    $mimes['hdr'] = 'application/octet-stream';
    $mimes['exr'] = 'application/octet-stream';
    return $mimes;
}

add_filter( 'upload_mimes', 'dprcu_mime_types' );
function dprcu_admin_scripts(  $hook  ) {
    // IMPORTANT: Check if we are on your specific settings page.
    // Replace 'dprcu-settings' with the slug you used in add_submenu_page
    if ( strpos( $hook, 'dprcu-settings' ) === false ) {
        return;
    }
    // Enqueue the native WordPress media uploader scripts
    wp_enqueue_media();
    // Enqueue HDR uploader script
    wp_enqueue_script(
        'dprcu-hdr-uploader',
        plugins_url( 'js/hdr-uploader.js', __FILE__ ),
        array('jquery', 'media-upload', 'media-views'),
        '1.0',
        true
    );
}

add_action( 'admin_enqueue_scripts', 'dprcu_admin_scripts' );
// Add Menu Item
function dprcu_register_options_page() {
    // Isometric cube SVG icon — three filled faces with transparent gaps for edge lines.
    // Uses fill="black" so WordPress admin color scheme is applied automatically via CSS.
    $icon_svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">' . '<polygon fill="black" points="10,1.5 17.5,5.75 10,9.5 2.5,5.75"/>' . '<polygon fill="black" points="2.5,6.75 9.5,10.25 9.5,18.5 2.5,14.25"/>' . '<polygon fill="black" points="17.5,6.75 17.5,14.25 10.5,18.5 10.5,10.25"/>' . '</svg>';
    add_menu_page(
        '3D Customizer',
        // Page Title
        '3D Product Customizer',
        // Menu Title (Top-level)
        'manage_options',
        // Capability
        'dprcu-settings',
        // Slug
        'dprcu_settings_page_html',
        // Callback
        'data:image/svg+xml;base64,' . base64_encode( $icon_svg ),
        // Icon
        58
    );
}

add_action( 'admin_menu', 'dprcu_register_options_page', 9 );
// Priority 9 to run before Freemius
// Register Settings
function dprcu_register_settings() {
    register_setting( 'dprcu_options', 'dprcu_settings', array(
        'sanitize_callback' => 'dprcu_sanitize_settings',
    ) );
    add_settings_section(
        'display_section',
        'Display Options',
        null,
        'dprcu-settings'
    );
    // Display Method
    add_settings_field(
        'display_method',
        'Display Method',
        'dprcu_render_display_method',
        'dprcu-settings',
        'display_section',
        array(
            'key'         => 'display_method',
            'default'     => 'auto',
            'description' => __( 'Choose how to display the customizer on product pages.', '3d-product-customizer' ),
        )
    );
    add_settings_section(
        'default_section',
        'Scene Configuration',
        null,
        'dprcu-settings'
    );
    // Camera Distance Multiplier (auto-framing relative to model size)
    add_settings_field(
        'camera_distance_multiplier',
        'Camera Distance (relative to model)',
        'dprcu_render_float',
        'dprcu-settings',
        'default_section',
        array(
            'key'         => 'camera_distance_multiplier',
            'default'     => 1.2,
            'min'         => 0.5,
            'max'         => 3.0,
            'step'        => 0.1,
            'description' => __( 'Adjust how far the camera is from the model. 1.0 = automatic framing, < 1.0 = closer (more zoom), > 1.0 = farther (more space around model).', '3d-product-customizer' ),
        )
    );
    // Backgrounds
    add_settings_field(
        'bg_colors',
        'Background Colors',
        'dprcu_render_textarea',
        'dprcu-settings',
        'default_section',
        array(
            'key' => 'bg_colors',
        )
    );
    // --- NEW: Zoom Limits ---
    add_settings_field(
        'zoom_limits',
        'Zoom Range (Min, Max)',
        'dprcu_render_minmax',
        'dprcu-settings',
        'default_section',
        array(
            'key'     => 'zoom_limits',
            'default' => array(1, 10),
        )
    );
    add_settings_field(
        'hdr_file',
        'HDR Environment Map',
        'dprcu_render_hdr_file',
        'dprcu-settings',
        'default_section',
        array(
            'key' => 'hdr_file',
        )
    );
    // Premium-only: Hide watermark
    if ( dprcu_fs()?->can_use_premium_code__premium_only() ) {
        add_settings_field(
            'hide_watermark',
            'Hide Watermark',
            'dprcu_render_hide_watermark__premium_only',
            'dprcu-settings',
            'default_section'
        );
        add_settings_field(
            'hotspot_enabled',
            'Hotspot Enabled',
            'dprcu_render_hotspot_enabled__premium_only',
            'dprcu-settings',
            'display_section',
            array(
                'key'         => 'hotspot_enabled',
                'default'     => 1,
                'description' => __( 'Toggle the visibility of interactive hotspots on the product.', '3d-product-customizer' ),
            )
        );
    }
    add_settings_section(
        'danger_section',
        'Advanced',
        null,
        'dprcu-settings'
    );
    add_settings_field(
        'delete_on_uninstall',
        'Delete data on uninstall',
        'dprcu_render_delete_on_uninstall',
        'dprcu-settings',
        'danger_section'
    );
    add_settings_field(
        'ar_button_display_method',
        'AR Button Display Method',
        'dprcu_render_ar_button_display_method',
        'dprcu-settings',
        'display_section',
        array(
            'key'         => 'ar_display_mode',
            'default'     => 'simple',
            'description' => __( 'Choose how to display the AR button on the customizer interface.', '3d-product-customizer' ),
        )
    );
}

add_action( 'admin_init', 'dprcu_register_settings' );
// Render Callbacks
function dprcu_settings_page_html() {
    ?>
	<div class="wrap">
		<h1><?php 
    esc_html_e( '3D Customizer Settings', '3d-product-customizer' );
    ?></h1>
		<form method="post" action="options.php">
			<?php 
    settings_fields( 'dprcu_options' );
    do_settings_sections( 'dprcu-settings' );
    submit_button();
    ?>
		</form>
	</div>
	<?php 
}

function dprcu_render_float(  $args  ) {
    $options = get_option( 'dprcu_settings' );
    $default = $args['default'] ?? 1.0;
    $val = $options[$args['key']] ?? $default;
    $min = $args['min'] ?? 0.0;
    $max = $args['max'] ?? 10.0;
    $step = $args['step'] ?? 0.1;
    $description = $args['description'] ?? '';
    ?>
	<input type="number" step="<?php 
    echo esc_attr( $step );
    ?>" min="<?php 
    echo esc_attr( $min );
    ?>" max="<?php 
    echo esc_attr( $max );
    ?>" name="dprcu_settings[<?php 
    echo esc_attr( $args['key'] );
    ?>]"
		value="<?php 
    echo esc_attr( (float) $val );
    ?>" style="width:100px;">
	<?php 
    if ( $description ) {
        ?>
		<p class="description"><?php 
        echo esc_html( $description );
        ?></p>
	<?php 
    }
    ?>
	<?php 
}

/**
 * Render display method selector.
 */
function dprcu_render_display_method(  $args  ) {
    $options = get_option( 'dprcu_settings' );
    $val = $options[$args['key']] ?? 'auto';
    $description = $args['description'] ?? '';
    ?>
	<select name="dprcu_settings[<?php 
    echo esc_attr( $args['key'] );
    ?>]" style="width:250px;">
		<option value="auto" <?php 
    selected( $val, 'auto' );
    ?>>
			<?php 
    esc_html_e( 'Automatic (before product summary)', '3d-product-customizer' );
    ?>
		</option>
		<option value="manual_placement" <?php 
    selected( $val, 'manual_placement' );
    ?>>
			<?php 
    esc_html_e( 'Manual Placement', '3d-product-customizer' );
    ?>
		</option>
		<option value="manual_hook" <?php 
    selected( $val, 'manual_hook' );
    ?>>
			<?php 
    esc_html_e( 'Manual Hook (dprcu_display_customizer)', '3d-product-customizer' );
    ?>
		</option>
	</select>
	<?php 
    if ( $description ) {
        ?>
		<p class="description">
			<?php 
        echo esc_html( $description );
        ?><br>
			<strong><?php 
        esc_html_e( 'Options:', '3d-product-customizer' );
        ?></strong><br>
			- <?php 
        esc_html_e( 'Automatic: Displays before product summary (default behavior)', '3d-product-customizer' );
        ?><br>
			- <?php 
        esc_html_e( 'Manual Placement: Use [dprcu-customizer] shortcode or block in editor to display', '3d-product-customizer' );
        ?><br>
			- <?php 
        esc_html_e( 'Manual Hook: Use do_action("dprcu_display_customizer") in your theme', '3d-product-customizer' );
        ?>
		</p>
	<?php 
    }
    ?>
	<?php 
}

function dprcu_render_textarea(  $args  ) {
    $options = get_option( 'dprcu_settings' );
    $val = $options[$args['key']] ?? "#f0f0f0\n#ffffff\n#222222";
    ?>
	<textarea name="dprcu_settings[<?php 
    echo esc_attr( $args['key'] );
    ?>]" rows="5"
		cols="50"><?php 
    echo esc_textarea( $val );
    ?></textarea>
	<p class="description"><?php 
    esc_html_e( 'Enter one Hex color code per line (e.g. #ffffff).', '3d-product-customizer' );
    ?></p>
	<?php 
}

function dprcu_render_delete_on_uninstall() {
    $options = get_option( 'dprcu_settings' );
    $checked = !empty( $options['delete_on_uninstall'] );
    ?>
	<label>
		<input type="checkbox" name="dprcu_settings[delete_on_uninstall]" value="1" <?php 
    checked( $checked );
    ?>>
		<?php 
    esc_html_e( 'When this plugin is deleted, permanently remove all steps, materials, and settings.', '3d-product-customizer' );
    ?>
	</label>
	<p class="description" style="color:#b32d2e;"><?php 
    esc_html_e( 'Leave unchecked to keep your data safe when switching between free and premium versions.', '3d-product-customizer' );
    ?></p>
	<?php 
}

function dprcu_render_ar_button_display_method() {
    $options = get_option( 'dprcu_settings' );
    $val = $options['ar_display_mode'] ?? 'simple';
    ?>
	<select name="dprcu_settings[ar_display_mode]" style="width:250px;">
		<option value="simple" <?php 
    selected( $val, 'simple' );
    ?>>
			<?php 
    esc_html_e( 'Simple (Floating AR Button)', '3d-product-customizer' );
    ?>
		</option>
		<option value="detailed" <?php 
    selected( $val, 'detailed' );
    ?>>
			<?php 
    esc_html_e( 'Detailed (AR Button with Label)', '3d-product-customizer' );
    ?>
		</option>
		<option value="off" <?php 
    selected( $val, 'off' );
    ?>>
			<?php 
    esc_html_e( 'Off (No AR Button in Customizer)', '3d-product-customizer' );
    ?>
		</option>
	</select>
	<p class="description">
		<?php 
    esc_html_e( 'Choose how the AR button is displayed in the customizer interface.', '3d-product-customizer' );
    ?><br>
		- <?php 
    esc_html_e( 'Simple: A floating button with just an icon (default)', '3d-product-customizer' );
    ?><br>
		- <?php 
    esc_html_e( 'Detailed: A larger button with both icon and text label for clarity', '3d-product-customizer' );
    ?><br>
		- <?php 
    esc_html_e( 'Off: AR button will not be shown in the customizer interface, but AR functionality will still be available on the front-end if there is a button with the id #btn-view-ar', '3d-product-customizer' );
    ?>
	</p>
	<?php 
}

// Sanitize
function dprcu_sanitize_settings(  $input  ) {
    $new_input = array();
    // Display Method
    if ( isset( $input['display_method'] ) ) {
        $allowed_methods = array('auto', 'manual_placement', 'manual_hook');
        $method = sanitize_text_field( $input['display_method'] );
        $new_input['display_method'] = ( in_array( $method, $allowed_methods, true ) ? $method : 'auto' );
    }
    // Camera Distance Multiplier
    if ( isset( $input['camera_distance_multiplier'] ) ) {
        $multiplier = floatval( $input['camera_distance_multiplier'] );
        // Clamp to reasonable range
        $new_input['camera_distance_multiplier'] = max( 0.5, min( 3.0, $multiplier ) );
    }
    // Zoom Limits
    if ( isset( $input['zoom_limits'] ) ) {
        $new_input['zoom_limits'] = array_map( 'floatval', $input['zoom_limits'] );
    }
    // Background Colors
    if ( isset( $input['bg_colors'] ) ) {
        $bgs = preg_split( '/\\r\\n|[\\r\\n]/', $input['bg_colors'] );
        $clean_bgs = array();
        foreach ( $bgs as $bg ) {
            $bg = sanitize_hex_color( $bg );
            if ( $bg ) {
                $clean_bgs[] = $bg;
            }
        }
        $new_input['bg_colors'] = implode( "\n", $clean_bgs );
    }
    // HDR File (The Missing Link)
    if ( isset( $input['hdr_file'] ) ) {
        // esc_url_raw is safe for saving URLs to database
        $new_input['hdr_file'] = esc_url_raw( $input['hdr_file'] );
    }
    // Hide watermark — only true when the checkbox is explicitly submitted (premium only)
    // Named with __premium_only so this block is stripped from free build
    if ( dprcu_fs()?->can_use_premium_code__premium_only() ) {
        $new_input['hide_watermark'] = ( !empty( $input['hide_watermark'] ) ? 1 : 0 );
    }
    if ( isset( $input['ar_display_mode'] ) ) {
        $allowed_modes = array('simple', 'detailed', 'off');
        $mode = sanitize_text_field( $input['ar_display_mode'] );
        $new_input['ar_display_mode'] = ( in_array( $mode, $allowed_modes, true ) ? $mode : 'simple' );
    }
    if ( dprcu_fs()?->can_use_premium_code__premium_only() ) {
        $new_input['hotspot_enabled'] = ( !empty( $input['hotspot_enabled'] ) ? 1 : 0 );
    }
    // Delete on uninstall — only true when the checkbox is explicitly submitted
    $new_input['delete_on_uninstall'] = ( !empty( $input['delete_on_uninstall'] ) ? 1 : 0 );
    return $new_input;
}

// --- Render Callback for Min/Max ---
function dprcu_render_minmax(  $args  ) {
    $options = get_option( 'dprcu_settings' );
    $defaults = $args['default'];
    $vals = $options[$args['key']] ?? $defaults;
    ?>
	<input type="number" step="0.1" name="dprcu_settings[<?php 
    echo esc_attr( $args['key'] );
    ?>][]"
		value="<?php 
    echo esc_attr( $vals[0] );
    ?>" placeholder="Min" style="width:80px;">
	<input type="number" step="0.1" name="dprcu_settings[<?php 
    echo esc_attr( $args['key'] );
    ?>][]"
		value="<?php 
    echo esc_attr( $vals[1] );
    ?>" placeholder="Max" style="width:80px;">
	<p class="description"><?php 
    esc_html_e( 'Minimum distance (Zoom In) and Maximum distance (Zoom Out).', '3d-product-customizer' );
    ?></p>
	<?php 
}

function dprcu_render_hdr_file(  $args  ) {
    // Get current value
    $options = get_option( 'dprcu_settings' );
    $val = $options[$args['key']] ?? '';
    // Render Input and Button
    ?>
	<div class="hdr-upload-wrapper">
		<input type="text" id="dprcu_hdr_url" name="dprcu_settings[<?php 
    echo esc_attr( $args['key'] );
    ?>]"
			value="<?php 
    echo esc_attr( $val );
    ?>" placeholder="https://.../studio.hdr" style="width:350px;">

		<input type="button" id="upload_hdr_button" class="button" value="Select HDR from Media Library">

		<p class="description"><?php 
    esc_html_e( 'Upload an .hdr or .exr file to light the scene realistically.', '3d-product-customizer' );
    ?></p>

		<?php 
    if ( $val ) {
        ?>
			<p style="margin-top:5px; color:#666; font-size:12px;">
				<strong>Current File:</strong> <?php 
        echo esc_html( basename( $val ) );
        ?>
			</p>
		<?php 
    }
    ?>
	</div>
	<?php 
}

/**
 * Display plugin footer with authors/credits on all dprcu admin pages.
 *
 * Shows author information in the admin footer.
 */
function dprcu_admin_footer_text(  $text  ) {
    global $pagenow;
    // Check if we're on a dprcu plugin admin page
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only context check, no form processing
    if ( !isset( $_GET['page'] ) || strpos( sanitize_text_field( wp_unslash( $_GET['page'] ) ), 'dprcu' ) === false ) {
        return $text;
    }
    return sprintf(
        wp_kses_post( 
            /* translators: %1$s = plugin author URL, %2$s = plugin author name, %3$s = demo URL */
            __( '3D Product Customizer by <a href="%1$s" target="_blank">%2$s</a> | <a href="%3$s" target="_blank">Demo</a>', '3d-product-customizer' )
         ),
        'https://deosebitsoft.ro/',
        'deosebIT Soft',
        'https://web-support.eu/'
    );
}

add_filter( 'admin_footer_text', 'dprcu_admin_footer_text' );