<?php

/**
 * Admin functionality.
 * 
 * @author Nikunj Hatkar
 * @link https://github.com/nikunj8866
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
    // Prevent direct access.
}
/**
 * Admin class for Broken Image Fallback plugin.
 */
class Broken_Image_Fallback_Admin {
    /**
     * Constructor.
     *
     * Initializes the admin functionality.
     */
    public function __construct() {
        add_action( 'admin_menu', array($this, 'add_admin_menu') );
        add_action( 'admin_init', array($this, 'admin_init') );
        add_action( 'admin_enqueue_scripts', array($this, 'admin_enqueue_scripts') );
    }

    /**
     * Enqueue admin scripts and styles.
     *
     * @param string $hook The current admin page.
     */
    public function admin_enqueue_scripts( $hook ) {
        // Check for our specific admin page.
        if ( 'toplevel_page_broken-image-fallback' !== $hook ) {
            return;
        }
        wp_enqueue_media();
        wp_enqueue_script(
            'brokimfa-admin',
            BROKIMFA_PLUGIN_URL . 'assets/admin.js',
            array('jquery', 'media-upload'),
            BROKIMFA_VERSION,
            true
        );
        wp_enqueue_style(
            'brokimfa-admin',
            BROKIMFA_PLUGIN_URL . 'assets/admin.css',
            array(),
            BROKIMFA_VERSION
        );
    }

    /**
     * Add admin menu.
     *
     * @return void
     */
    public function add_admin_menu() {
        $page_title = __( 'Broken Image Fallback', 'broken-image-fallback' );
        add_menu_page(
            $page_title,
            $page_title,
            'manage_options',
            'broken-image-fallback',
            array($this, 'admin_page'),
            $this->get_menu_icon(),
            30
        );
        add_submenu_page(
            'broken-image-fallback',
            __( 'Settings', 'broken-image-fallback' ),
            __( 'Settings', 'broken-image-fallback' ),
            'manage_options',
            'broken-image-fallback'
        );
    }

    /**
     * Get menu icon.
     *
     * @return string Base64 encoded SVG icon data URI.
     */
    private function get_menu_icon() {
        $color = '#a0a5aa';
        $svg_icon = 'data:image/svg+xml;base64,' . base64_encode( '
			<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
				<g fill="' . $color . '">
					<rect x="2" y="3" width="16" height="12" fill="none" stroke="currentColor" stroke-width="1.5" rx="1"/>
					<path d="M5 7l3 3 2-2 3 3v3H5V7z" fill="currentColor" opacity="0.3"/>
					<circle cx="7" cy="6.5" r="1" fill="currentColor" opacity="0.5"/>
					<path d="M14 16l2-2-2-2v1.5h-2v1h2V16z" fill="' . (( '#00a32a' === $color ? '#00ff88' : '#0073aa' )) . '"/>
					<rect x="15" y="13" width="3" height="2" fill="' . (( '#00a32a' === $color ? '#00ff88' : '#0073aa' )) . '" opacity="0.7" rx="0.5"/>
				</g>
			</svg>
		' );
        return $svg_icon;
    }

    /**
     * Initialize admin settings.
     *
     * @return void
     */
    public function admin_init() {
        register_setting( 'brokimfa_settings', 'brokimfa_options', array($this, 'sanitize_options') );
        add_settings_section(
            'brokimfa_main_section',
            __( 'Basic Configuration', 'broken-image-fallback' ),
            array($this, 'main_section_callback'),
            'brokimfa_settings'
        );
        add_settings_section(
            'brokimfa_performance_section',
            __( 'Performance Settings', 'broken-image-fallback' ),
            array($this, 'performance_section_callback'),
            'brokimfa_settings'
        );
        // Add settings fields
        $this->add_settings_fields();
    }

    /**
     * Add settings fields.
     *
     * @return void
     */
    private function add_settings_fields() {
        // Basic settings (always available)
        add_settings_field(
            'default_image_url',
            __( 'Default Fallback Image', 'broken-image-fallback' ),
            array($this, 'default_image_callback'),
            'brokimfa_settings',
            'brokimfa_main_section'
        );
        add_settings_field(
            'lazy_loading_compat',
            __( 'Lazy Loading Compatibility', 'broken-image-fallback' ),
            array($this, 'lazy_loading_callback'),
            'brokimfa_settings',
            'brokimfa_performance_section'
        );
    }

    /**
     * Sanitize options.
     *
     * @param array $input The input options to sanitize.
     * @return array The sanitized options.
     */
    public function sanitize_options( $input ) {
        $sanitized = array();
        // Basic settings (always allowed)
        $sanitized['default_image_url'] = esc_url_raw( $input['default_image_url'] );
        $sanitized['lazy_loading_compat'] = !empty( $input['lazy_loading_compat'] );
        // For free users, set PRO features to default values
        $sanitized['fallback_method'] = 'default_image';
        return $sanitized;
    }

    /**
     * Main section callback.
     */
    public function main_section_callback() {
        echo '<p>' . esc_html__( 'Basic image fallback configuration. Upgrade to Pro for advanced features!', 'broken-image-fallback' ) . '</p>';
    }

    /**
     * Advanced section callback.
     */
    public function advanced_section_callback() {
        echo '<p>' . esc_html__( 'Advanced fallback methods and customization options.', 'broken-image-fallback' ) . '</p>';
    }

    /**
     * Performance section callback.
     */
    public function performance_section_callback() {
        echo '<p>' . esc_html__( 'Performance and compatibility settings.', 'broken-image-fallback' ) . '</p>';
    }

    /**
     * WordPress section callback.
     */
    public function wordpress_section_callback() {
        echo '<p>' . esc_html__( 'WordPress-specific features including Featured Images and Gutenberg blocks.', 'broken-image-fallback' ) . '</p>';
    }

    /**
     * Display default image URL field.
     *
     * @return void
     */
    public function default_image_callback() {
        $options = Broken_Image_Fallback::get_options();
        $url = ( isset( $options['default_image_url'] ) ? $options['default_image_url'] : '' );
        ?>
		<div class="brokimfa-image-upload">
			<input type="url" name="brokimfa_options[default_image_url]" id="default_image_url" value="<?php 
        echo esc_attr( $url );
        ?>" class="regular-text" placeholder="<?php 
        esc_html_e( 'Enter fallback image URL', 'broken-image-fallback' );
        ?>" />
			<button type="button" class="button" id="upload_image_button"><?php 
        esc_html_e( 'Select Image', 'broken-image-fallback' );
        ?></button>
			<?php 
        if ( $url ) {
            ?>
				<div class="brokimfa-image-preview">
					<img src="<?php 
            echo esc_url( $url );
            ?>" style="max-width: 150px; max-height: 100px; margin-top: 10px;" />
				</div>
			<?php 
        }
        ?>
		</div>
		<p class="description"><?php 
        esc_html_e( 'Select or enter URL of the default image to use as fallback.', 'broken-image-fallback' );
        ?></p>
		<?php 
    }

    /**
     * Display lazy loading compatibility field.
     *
     * @return void
     */
    public function lazy_loading_callback() {
        $options = Broken_Image_Fallback::get_options();
        $lazy = ( isset( $options['lazy_loading_compat'] ) ? $options['lazy_loading_compat'] : true );
        ?>
		<label>
			<input type="checkbox" name="brokimfa_options[lazy_loading_compat]" id="lazy_loading_compat" value="1" <?php 
        checked( $lazy, true );
        ?> />
			<?php 
        esc_html_e( 'Enable compatibility with lazy loading plugins', 'broken-image-fallback' );
        ?>
		</label>
		<p class="description"><?php 
        esc_html_e( 'Uses MutationObserver to handle dynamically loaded images.', 'broken-image-fallback' );
        ?></p>
		<?php 
    }

    /**
     * Admin page callback.
     *
     * @return void
     */
    public function admin_page() {
        $header_class = 'brokimfa-header-free';
        $fill_color = '#72aee6';
        ?>
		<div class="wrap">
			<div class="brokimfa-header <?php 
        echo esc_attr( $header_class );
        ?>">
				<div class="brokimfa-header-icon">
					<svg width="32" height="32" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">
						<g fill="white">
							<rect x="3" y="5" width="26" height="18" fill="none" stroke="currentColor" stroke-width="2" rx="2"/>
							<path d="M7 11l5 5 3-3 5 5v5H7V11z" fill="currentColor" opacity="0.3"/>
							<circle cx="11" cy="10" r="1.5" fill="currentColor" opacity="0.5"/>
							<path d="M22 25l3-3-3-3v2h-3v2h3v2z" fill="<?php 
        echo esc_attr( $fill_color );
        ?>"/>
						</g>
					</svg>
				</div>
				<div class="brokimfa-header-text">
					<?php 
        ?>
						<h1><?php 
        esc_html_e( 'Broken Image Fallback', 'broken-image-fallback' );
        ?></h1>
					<?php 
        ?>
					<p class="brokimfa-subtitle"><?php 
        esc_html_e( 'High-performance image fallback system with zero page load impact', 'broken-image-fallback' );
        ?></p>
				</div>
				<?php 
        if ( brokimfa_fs()->is_free_plan() ) {
            ?>
				<div class="brokimfa-header-upgrade">
					<a href="<?php 
            echo esc_url( Broken_Image_Fallback::get_upgrade_url( 'header' ) );
            ?>" class="brokimfa-upgrade-button">
						<?php 
            esc_html_e( 'Upgrade to Pro', 'broken-image-fallback' );
            ?>
					</a>
				</div>
				<?php 
        }
        ?>
			</div>
			
			<div class="brokimfa-admin-content brokimfa-flex">
				<?php 
        $header_class = 'free';
        ?>
				<div class="brokimfa-flex-col brokimfa-settings-container <?php 
        echo esc_attr( $header_class );
        ?>">
					<form method="post" action="options.php">
						<?php 
        settings_fields( 'brokimfa_settings' );
        do_settings_sections( 'brokimfa_settings' );
        submit_button(
            __( 'Save Settings', 'broken-image-fallback' ),
            'primary',
            'submit',
            true,
            array(
                'class' => 'brokimfa-save-button',
            )
        );
        ?>
				</form>
				</div>

				<?php 
        if ( brokimfa_fs()->is_free_plan() ) {
            ?>
				<div class="brokimfa-flex-col brokimfa-sidebar-container">
					<div class="brokimfa-upgrade-cta">
						<div class="brokimfa-upgrade-cta-content">
							<h3><?php 
            esc_html_e( '🚀 Unlock Pro Features', 'broken-image-fallback' );
            ?></h3>
							<div class="brokimfa-pro-features">
								<p class="brokimfa-pro-feature">
									<span class="dashicons dashicons-yes"></span>
									<?php 
            esc_html_e( 'Advanced Fallback Methods (Alt Text, Both, Hide)', 'broken-image-fallback' );
            ?>
								</p>
								<p class="brokimfa-pro-feature">
									<span class="dashicons dashicons-yes"></span>
									<?php 
            esc_html_e( 'WordPress Features (Featured Images, Gutenberg)', 'broken-image-fallback' );
            ?>
								</p>
								<p class="brokimfa-pro-feature">
									<span class="dashicons dashicons-yes"></span>
									<?php 
            esc_html_e( 'Custom CSS Styling & Fade Effects', 'broken-image-fallback' );
            ?>
								</p>
								<p class="brokimfa-pro-feature">
									<span class="dashicons dashicons-yes"></span>
									<?php 
            esc_html_e( 'Priority Support & Regular Updates', 'broken-image-fallback' );
            ?>
								</p>
							</div>
							<div class="brokimfa-upgrade-cta-actions">
								<a href="<?php 
            echo esc_url( Broken_Image_Fallback::get_upgrade_url( 'footer_cta' ) );
            ?>" class="button button-primary button-hero">
									<?php 
            esc_html_e( 'Upgrade to Pro Now', 'broken-image-fallback' );
            ?>
								</a>
								<p class="brokimfa-money-back"><?php 
            esc_html_e( '14-day money-back guarantee', 'broken-image-fallback' );
            ?></p>
							</div>
						</div>
					</div>
				</div>
				<?php 
        }
        ?>
			</div>
		</div>
		<?php 
    }

}
