<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }
class YXXSMWA_Admin {
    private static $i=null;
    public static function instance(){if(null===self::$i){self::$i=new self();}return self::$i;}
    private function __construct(){
        add_action('admin_menu',[$this,'add_settings_page']);
        add_action('admin_init',[$this,'register_settings']);
        add_action('admin_enqueue_scripts',[$this,'enqueue_assets']);
        add_action('admin_footer',[$this,'footer_scripts']);
        add_filter('plugin_action_links_'.YXXSMWA_PLUGIN_BASENAME,[$this,'plugin_action_links']);
    }

    public function add_settings_page(){
        add_options_page('YXX Smart Watermark Settings','YXX Smart Watermark','manage_options','yxx-smart-watermark',[$this,'render_settings_page']);
    }

    public function register_settings(){
        foreach(['yxxsmwa_text_enabled','yxxsmwa_text_content','yxxsmwa_text_size','yxxsmwa_text_color',
                 'yxxsmwa_text_opacity','yxxsmwa_position','yxxsmwa_image_sizes','yxxsmwa_auto_watermark',
                 'yxxsmwa_image_watermark_enabled','yxxsmwa_image_watermark_id','yxxsmwa_image_watermark_opacity'] as $k){
            register_setting('yxxsmwa_settings_group',$k,'sanitize_text_field');
        }
    }

    public function enqueue_assets($h){
        if($h!=='settings_page_yxx-smart-watermark') return;
        wp_enqueue_media();
        // Inline CSS enqueued properly
        $inline_css = $this->get_inline_css();
        if (!empty($inline_css)) {
            wp_add_inline_style('wp-admin', $inline_css);
        }
        // Inline JS enqueued properly
        // JS is output via admin_footer hook
    }

    private function get_inline_css() {
        return '
.yxxsmwa-position-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 4px;
    max-width: 360px;
}
.yxxsmwa-grid-cell {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 14px 8px 10px;
    border: 2px solid #ddd;
    border-radius: 8px;
    cursor: pointer;
    transition: all .15s ease;
    background: #f6f7f7;
    user-select: none;
}
.yxxsmwa-grid-cell:hover {
    border-color: #2271b1;
    background: #f0f6fc;
}
.yxxsmwa-grid-cell.yxxsmwa-grid-active {
    border-color: #2271b1;
    background: #e5f0fa;
    box-shadow: 0 0 0 1px #2271b1;
}
.yxxsmwa-grid-icon {
    font-size: 22px;
    line-height: 1.2;
}
.yxxsmwa-grid-label {
    font-size: 10px;
    color: #666;
    margin-top: 4px;
    white-space: nowrap;
}
.yxxsmwa-grid-active .yxxsmwa-grid-label {
    color: #2271b1;
    font-weight: 600;
}
.yxxsmwa-size-label {
    display: inline-block;
    min-width: 200px;
    margin: 4px 8px 4px 0;
    padding: 4px 0;
}
.yxxsmwa-size-label input {
    margin-right: 4px;
}
.wrap h2 {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #e5e5e5;
}
.wrap h2:first-of-type {
    border-top: none;
}
.yxxsmwa-pro-section {
    margin-top: 32px;
    padding-top: 8px;
    border-top: 2px solid #e5e5e5;
}
.yxxsmwa-pro-card {
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 24px;
    max-width: 640px;
}
.yxxsmwa-buy-btn {
    font-size: 14px;
    height: 40px;
    line-height: 38px;
    padding: 0 24px;
}
';
    }

    private function get_inline_js() {
        ob_start();
?>
function yxxsmwaSelectPosition(el){
    document.querySelectorAll(".yxxsmwa-grid-cell").forEach(function(c){
        c.classList.remove("yxxsmwa-grid-active");
    });
    el.classList.add("yxxsmwa-grid-active");
    document.getElementById("yxxsmwa_position").value = el.dataset.pos;
}
var yxxsmwaFrame = null;
function yxxsmwaSelectImage(){
    if(yxxsmwaFrame){ yxxsmwaFrame.open(); return; }
    yxxsmwaFrame = wp.media({
        title: "Select Watermark Image",
        button: { text: "Use as Watermark" },
        multiple: false,
        library: { type: "image" }
    });
    yxxsmwaFrame.on("select", function(){
        var att = yxxsmwaFrame.state().get("selection").first().toJSON();
        document.getElementById("yxxsmwa_image_watermark_id").value = att.id;
        document.getElementById("yxxsmwa_image_watermark_preview").innerHTML =
            '<img src="'+att.url+'" style="max-width:150px;max-height:150px;display:block;margin-bottom:8px;">';
        var rmBtns = document.querySelectorAll(".yxxsmwa-remove-img-btn");
        if(rmBtns.length > 0) rmBtns[0].style.display = "";
    });
    yxxsmwaFrame.open();
}
function yxxsmwaRemoveImage(){
    document.getElementById("yxxsmwa_image_watermark_id").value = "";
    document.getElementById("yxxsmwa_image_watermark_preview").innerHTML = "";
    var rmBtns = document.querySelectorAll(".yxxsmwa-remove-img-btn");
    if(rmBtns.length > 0) rmBtns[0].style.display = "none";
}
<?php
        return ob_get_clean();
    }

    public function footer_scripts(){
        $screen = get_current_screen();
        if(!$screen || $screen->id !== 'settings_page_yxx-smart-watermark') return;
        wp_print_inline_script_tag( $this->get_inline_js(), [ 'id' => 'yxx-smart-watermark-js' ] );
    }

    private function size_label($size){
        $dims = wp_get_registered_image_subsizes();
        if($size === 'full') return __('Original','yxx-smart-watermark');
        if(isset($dims[$size])){
            $w = $dims[$size]['width'];
            $h = $dims[$size]['height'];
            if(!$h) return "{$w}xauto";
            return "{$w}x{$h}";
        }
        return $size;
    }

    public function render_settings_page(){
        $s = YXXSMWA_Core::get_settings();
        if(!current_user_can('manage_options')) return;

        // Get image sizes with dimensions
        $registered = wp_get_registered_image_subsizes();
        $all_sizes = array_merge(['full'], array_keys($registered));
        $saved = get_option('yxxsmwa_image_sizes', []);
        if(empty($saved)) $saved = ['full', 'large'];
        ?>
        <div class="wrap">
        <h1><?php esc_html_e('YXX Smart Watermark Settings','yxx-smart-watermark'); ?></h1>
        <p><?php esc_html_e('Configure automatic watermark protection for your images.','yxx-smart-watermark'); ?></p>
        <form method="post" action="options.php">
        <?php settings_fields('yxxsmwa_settings_group'); ?>

        <!-- ============ Auto-Watermark ============ -->
        <h2><?php esc_html_e('Auto-Watermark','yxx-smart-watermark'); ?></h2>
        <table class="form-table">
        <tr>
            <th scope="row"><?php esc_html_e('Auto-watermark on upload','yxx-smart-watermark'); ?></th>
            <td><label><input type="checkbox" name="yxxsmwa_auto_watermark" value="1" <?php checked($s['auto_watermark']); ?>> <?php esc_html_e('Automatically apply watermark to new uploads','yxx-smart-watermark'); ?></label></td>
        </tr>
        </table>

        <!-- ============ Text Watermark ============ -->
        <h2><?php esc_html_e('Text Watermark','yxx-smart-watermark'); ?></h2>
        <table class="form-table">
        <tr>
            <th scope="row"><?php esc_html_e('Enable text watermark','yxx-smart-watermark'); ?></th>
            <td><label><input type="checkbox" name="yxxsmwa_text_enabled" value="1" <?php checked($s['text_enabled']); ?>> <?php esc_html_e('Add text watermark','yxx-smart-watermark'); ?></label></td>
        </tr>
        <tr>
            <th scope="row"><label for="yxxsmwa_text_content"><?php esc_html_e('Watermark text','yxx-smart-watermark'); ?></label></th>
            <td><input type="text" id="yxxsmwa_text_content" name="yxxsmwa_text_content" value="<?php echo esc_attr($s['text_content']); ?>" class="regular-text"></td>
        </tr>
        <tr>
            <th scope="row"><label for="yxxsmwa_text_size"><?php esc_html_e('Font size (pt)','yxx-smart-watermark'); ?></label></th>
            <td><select id="yxxsmwa_text_size" name="yxxsmwa_text_size">
                <?php $font_sizes = [8=>8,10=>10,12=>12,14=>14,16=>16,18=>18,20=>20,24=>24,28=>28,32=>32,36=>36,42=>42,48=>48,56=>56,64=>64];
                foreach($font_sizes as $v=>$l): ?>
                    <option value="<?php echo esc_attr($v); ?>" <?php selected($s['text_size'], $v); ?>><?php echo esc_html($l); ?>pt</option>
                <?php endforeach; ?>
            </select></td>
        </tr>
        <tr>
            <th scope="row"><label for="yxxsmwa_text_color"><?php esc_html_e('Text color','yxx-smart-watermark'); ?></label></th>
            <td><input type="color" id="yxxsmwa_text_color" name="yxxsmwa_text_color" value="<?php echo esc_attr($s['text_color']); ?>" style="width:50px;height:32px;padding:2px;border:1px solid #8c8f94;border-radius:4px;cursor:pointer;"></td>
        </tr>
        <tr>
            <th scope="row"><label for="yxxsmwa_text_opacity"><?php esc_html_e('Text opacity','yxx-smart-watermark'); ?></label></th>
            <td><input type="range" id="yxxsmwa_text_opacity" name="yxxsmwa_text_opacity" min="10" max="100" value="<?php echo (int)$s['text_opacity']; ?>"
                       oninput="document.getElementById('yxxsmwa_text_opacity_val').textContent=this.value">
                <span id="yxxsmwa_text_opacity_val"><?php echo (int)$s['text_opacity']; ?></span>%</td>
        </tr>
        </table>

        <!-- ============ Image / Logo Watermark ============ -->
        <h2><?php esc_html_e('Image / Logo Watermark','yxx-smart-watermark'); ?></h2>
        <table class="form-table">
        <tr>
            <th scope="row"><?php esc_html_e('Enable image watermark','yxx-smart-watermark'); ?></th>
            <td><label><input type="checkbox" name="yxxsmwa_image_watermark_enabled" value="1" <?php checked($s['img_enabled']); ?>> <?php esc_html_e('Overlay image/logo','yxx-smart-watermark'); ?></label></td>
        </tr>
        <tr>
            <th scope="row"><?php esc_html_e('Watermark image','yxx-smart-watermark'); ?></th>
            <td>
                <input type="hidden" id="yxxsmwa_image_watermark_id" name="yxxsmwa_image_watermark_id" value="<?php echo (int)$s['img_id']; ?>">
                <div id="yxxsmwa_image_watermark_preview"><?php
                    if($s['img_id'] && wp_get_attachment_image_url($s['img_id'])):
                        echo '<img src="'.esc_url(wp_get_attachment_image_url($s['img_id'],'thumbnail')).'" style="max-width:150px;max-height:150px;display:block;margin-bottom:8px;">';
                    endif;
                ?></div>
                <button type="button" class="button" onclick="yxxsmwaSelectImage()"><?php esc_html_e('Select Image','yxx-smart-watermark'); ?></button>
                <button type="button" class="button yxxsmwa-remove-img-btn" onclick="yxxsmwaRemoveImage()"<?php echo $s['img_id']?'':' style="display:none"'; ?>><?php esc_html_e('Remove','yxx-smart-watermark'); ?></button>
            </td>
        </tr>
        <tr>
            <th scope="row"><label for="yxxsmwa_image_watermark_opacity"><?php esc_html_e('Image opacity','yxx-smart-watermark'); ?></label></th>
            <td><input type="range" id="yxxsmwa_image_watermark_opacity" name="yxxsmwa_image_watermark_opacity" min="10" max="100" value="<?php echo (int)$s['img_opacity']; ?>"
                       oninput="document.getElementById('yxxsmwa_img_opacity_val').textContent=this.value">
                <span id="yxxsmwa_img_opacity_val"><?php echo (int)$s['img_opacity']; ?></span>%</td>
        </tr>
        </table>

        <!-- ============ Position (9-grid) ============ -->
        <h2><?php esc_html_e('Watermark Position','yxx-smart-watermark'); ?></h2>
        <table class="form-table">
        <tr>
            <th scope="row"><?php esc_html_e('Position','yxx-smart-watermark'); ?></th>
            <td>
                <input type="hidden" name="yxxsmwa_position" id="yxxsmwa_position" value="<?php echo esc_attr($s['position']); ?>">
                <div class="yxxsmwa-position-grid">
                    <?php
                    $positions = [
                        'top-left'      => '↖', 'top-center'      => '⬆', 'top-right'      => '↗',
                        'center-left'   => '⬅', 'center'          => '◎', 'center-right'   => '➡',
                        'bottom-left'   => '↙', 'bottom-center'    => '⬇', 'bottom-right'   => '↘',
                    ];
                    foreach($positions as $val => $icon):
                        $active = ($s['position'] === $val) ? ' yxxsmwa-grid-active' : '';
                    ?>
                        <div class="yxxsmwa-grid-cell<?php echo esc_attr($active); ?>" data-pos="<?php echo esc_attr($val); ?>" onclick="yxxsmwaSelectPosition(this)">
                            <span class="yxxsmwa-grid-icon"><?php echo esc_html($icon); ?></span>
                            <span class="yxxsmwa-grid-label"><?php echo esc_html( ucwords(str_replace('-',' ',$val)) ); ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>
                <p class="description"><?php esc_html_e('Click a position to place the watermark','yxx-smart-watermark'); ?></p>
            </td>
        </tr>
        </table>

        <!-- ============ Image Sizes ============ -->
        <h2><?php esc_html_e('Target Image Sizes','yxx-smart-watermark'); ?></h2>
        <table class="form-table">
        <tr>
            <th scope="row"><?php esc_html_e('Apply watermark to','yxx-smart-watermark'); ?></th>
            <td>
                <fieldset>
                <?php foreach($all_sizes as $size):
                    $label = $this->size_label($size);
                    $checked = in_array($size, $saved) ? 'checked' : '';
                ?>
                    <label class="yxxsmwa-size-label">
                        <input type="checkbox" name="yxxsmwa_image_sizes[]" value="<?php echo esc_attr($size); ?>" <?php echo esc_attr($checked); ?>>
                        <?php echo esc_html($label); ?>
                    </label>
                <?php endforeach; ?>
                </fieldset>
                <p class="description"><?php esc_html_e('Which image sizes will have the watermark applied on upload','yxx-smart-watermark'); ?></p>
            </td>
        </tr>
        </table>

        <?php submit_button(__('Save Settings','yxx-smart-watermark')); ?>
        </form>
        </div>

        <!-- ====== Pro Features (info only, no locked code) ====== -->
        <div class="yxxsmwa-pro-section">
            <h2><?php esc_html_e('Pro Features','yxx-smart-watermark'); ?> <span class="yxxsmwa-badge-pro">PRO</span></h2>
            <div class="yxxsmwa-pro-card">
                <p><?php esc_html_e('The Pro version is a separate plugin. It includes all free features plus:','yxx-smart-watermark'); ?></p>
                <ul class="yxxsmwa-feature-list">
                    <li><strong><?php esc_html_e('Bulk Watermark','yxx-smart-watermark'); ?></strong>  &mdash;  <?php esc_html_e('Apply watermark to all existing images in Media Library with one click.','yxx-smart-watermark'); ?></li>
                    <li><strong><?php esc_html_e('Media Bulk Action','yxx-smart-watermark'); ?></strong>  &mdash;  <?php esc_html_e('Select multiple images and watermark them instantly from the Media Library list view.','yxx-smart-watermark'); ?></li>
                    <li><strong><?php esc_html_e('Multiple Templates','yxx-smart-watermark'); ?></strong>  &mdash;  <?php esc_html_e('Create and save different watermark presets (text + image logo combinations) and switch between them anytime.','yxx-smart-watermark'); ?></li>
                    <li><strong><?php esc_html_e('Per-Image Control','yxx-smart-watermark'); ?></strong>  &mdash;  <?php esc_html_e('Enable or disable watermarking on individual images from the Media Library edit screen.','yxx-smart-watermark'); ?></li>
                    <li><strong><?php esc_html_e('Priority Support','yxx-smart-watermark'); ?></strong>  &mdash;  <?php esc_html_e('Email support within 24 hours.','yxx-smart-watermark'); ?></li>
                </ul>
                <p style="margin-top:16px;">
                    <strong><?php echo esc_html('$12.99/year'); ?></strong>
                    &mdash;
                    <a href="<?php echo esc_url(YXXSMWA_UPGRADE_URL); ?>" class="button button-primary" target="_blank" rel="noopener">
                        <?php esc_html_e('Upgrade to Pro','yxx-smart-watermark'); ?>
                    </a>
                </p>
            </div>
        </div>
        <?php
    }

    public function plugin_action_links($links){
        $settings = '<a href="'.admin_url('options-general.php?page=yxx-smart-watermark').'">'.esc_html__('Settings','yxx-smart-watermark').'</a>';
        array_unshift($links, $settings);
        return $links;
    }
}
