<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Add Admin Menu
add_action( 'admin_menu', 'cafi_add_admin_menu' );

function cafi_add_admin_menu() {
	$page_hook = add_menu_page(
		'Custom Auto Featured Image',
		'AutoFeatured',
		'manage_options',
		'auto-featured-image',
		'cafi_options_page_html',
        'dashicons-format-image',
        20
	);
    
    $hooks = [$page_hook];
    
    // Add Submenus (points to same slug/callback but with query args handled by JS/Main)
    // 1. Overview (Default)
    $hooks[] = add_submenu_page(
        'auto-featured-image',
        'Overview',
        'Overview',
        'manage_options',
        'auto-featured-image', // Same slug as parent
        'cafi_options_page_html'
    );

    // 2. Settings
    $hooks[] = add_submenu_page(
        'auto-featured-image',
        'Settings',
        'Settings',
        'manage_options',
        'auto-featured-image-settings',
        'cafi_options_page_html'
    );

    // 3. Templates
    $hooks[] = add_submenu_page(
        'auto-featured-image',
        'Templates',
        'Templates',
        'manage_options',
        'auto-featured-image-templates',
        'cafi_options_page_html'
    );

    // Enqueue Assets only on THESE pages
    add_action( 'admin_enqueue_scripts', function($hook) use ($hooks) {
        if ( ! in_array($hook, $hooks) ) {
            return;
        }

        // Enqueue Media Uploader scripts
        wp_enqueue_media();

        // Pickr (Local)
        wp_enqueue_style( 'pickr-css', plugin_dir_url( __FILE__ ) . 'assets/vendor/pickr/themes/classic.min.css', [], '1.9.1' );
        wp_enqueue_script( 'pickr-js', plugin_dir_url( __FILE__ ) . 'assets/vendor/pickr/pickr.min.js', [], '1.9.1', true );

        wp_enqueue_style( 
            'cafi-dashboard-css', 
            plugin_dir_url( __FILE__ ) . 'assets/dashboard.css', 
            [], 
            '1.0.0' 
        );
        
        // Google Fonts (Standard Enqueue)
        wp_enqueue_style( 'cafi-google-fonts', 'https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap', [], '1.0.0' );

        wp_enqueue_script( 
            'cafi-dashboard-js', 
            plugin_dir_url( __FILE__ ) . 'assets/dashboard.js', 
            ['jquery', 'pickr-js', 'wp-color-picker'], 
            CAFI_VERSION, 
            true 
        );
        
        // Pass Localized Data
        wp_localize_script( 'cafi-dashboard-js', 'cafiData', [
            'ajaxUrl'    => admin_url( 'admin-ajax.php' ),
            'nonce'      => wp_create_nonce( 'cafi_nonce' ),
            'currentTab' => $current_tab,
            'fontData'   => CAFI_Font_Manager::get_instance()->get_fonts_data()
        ]);
        
        // Color Picker
        wp_enqueue_style( 'wp-color-picker' );
    });
}

// Register Settings
add_action( 'admin_init', 'cafi_settings_init' );

function cafi_settings_init() {
	register_setting( 'cafi_plugin', 'cafi_settings', 'cafi_sanitize_settings' );
    // Note: We don't need add_settings_section/field anymore as we are rendering custom HTML forms
}

function cafi_sanitize_settings( $input ) {
    $new_input = array();
    $new_input['enable_plugin'] = isset( $input['enable_plugin'] ) ? 1 : 0;
    
    // Sanitize post types
    $new_input['post_types'] = array();
    if ( isset( $input['post_types'] ) && is_array( $input['post_types'] ) ) {
        foreach ( $input['post_types'] as $pt ) {
            $new_input['post_types'][] = sanitize_text_field( $pt );
        }
    }
    
    // Ensure at least 'post' is selected if empty (fixes missing UI field issue)
    if ( empty( $new_input['post_types'] ) ) {
        $new_input['post_types'] = ['post'];
    }

    $new_input['template'] = sanitize_text_field( $input['template'] );
    $new_input['text_position'] = sanitize_text_field( $input['text_position'] );
    // New Typography Settings
    $new_input['text_alignment'] = isset( $input['text_alignment'] ) ? sanitize_text_field( $input['text_alignment'] ) : 'center';
    $new_input['font_weight'] = isset( $input['font_weight'] ) ? sanitize_text_field( $input['font_weight'] ) : 'Regular';
    
    // Only save padding if it exists in input (Legacy)
    if ( isset( $input['padding'] ) ) {
        $new_input['padding'] = absint( $input['padding'] );
    }

    // New Margin Fields
    if ( isset( $input['padding_horizontal'] ) ) $new_input['padding_horizontal'] = absint( $input['padding_horizontal'] );
    if ( isset( $input['padding_vertical'] ) ) $new_input['padding_vertical'] = absint( $input['padding_vertical'] );
    
    if ( isset( $input['padding_top'] ) ) $new_input['padding_top'] = absint( $input['padding_top'] );
    if ( isset( $input['padding_right'] ) ) $new_input['padding_right'] = absint( $input['padding_right'] );
    if ( isset( $input['padding_bottom'] ) ) $new_input['padding_bottom'] = absint( $input['padding_bottom'] );
    if ( isset( $input['padding_left'] ) ) $new_input['padding_left'] = absint( $input['padding_left'] );
    
    // Generate Output Format
    $new_input['output_format'] = isset( $input['output_format'] ) ? sanitize_text_field( $input['output_format'] ) : 'png';

    // Logo Settings
    $new_input['logo_id'] = isset( $input['logo_id'] ) ? absint( $input['logo_id'] ) : 0;
    $new_input['logo_url'] = isset( $input['logo_url'] ) ? esc_url_raw( $input['logo_url'] ) : '';
    $new_input['logo_size'] = isset( $input['logo_size'] ) ? absint( $input['logo_size'] ) : 25; // Default 25%
    $new_input['logo_position'] = isset( $input['logo_position'] ) ? sanitize_text_field( $input['logo_position'] ) : 'bottom-right';
    
    // Split Offsets (Legacy 'logo_offset' mapped to both if needed, but we prefer new keys)
    $new_input['logo_offset_x'] = isset( $input['logo_offset_x'] ) ? absint( $input['logo_offset_x'] ) : 20;
    $new_input['logo_offset_y'] = isset( $input['logo_offset_y'] ) ? absint( $input['logo_offset_y'] ) : 20;
    // Legacy support not strictly needed for save, but useful to keep DB clean
    $new_input['logo_offset'] = $new_input['logo_offset_y']; // Fallback

    $new_input['font_family'] = sanitize_text_field( $input['font_family'] );
    // Use raw input but ensure valid range (default 60 if empty or too small?)
    // Actually just sanitizing here. View handles '40' default display. 
    // We will update View default too.
    $new_input['font_size'] = absint( $input['font_size'] );
    $new_input['font_color'] = sanitize_hex_color( $input['font_color'] );
    return $new_input;
}



// --- AJAX Handler for Saving Template Config ---
add_action( 'wp_ajax_cafi_save_template_config', 'cafi_ajax_save_template_config' );

function cafi_ajax_save_template_config() {
    // Check intent
    check_ajax_referer( 'cafi_nonce', 'security' );
    
    // Check permission
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( 'Permission denied' );
    }
    
    // Get params
    $template_id = isset( $_POST['template_id'] ) ? sanitize_text_field( wp_unslash( $_POST['template_id'] ) ) : '';
    
    // Check settings existence first
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $settings_input = isset( $_POST['settings'] ) ? wp_unslash( $_POST['settings'] ) : [];
    
    // Sanitize if it's an array
    $settings_raw = is_array( $settings_input ) ? array_map( 'sanitize_text_field', $settings_input ) : [];
    
    if ( empty( $template_id ) || empty( $settings_raw ) ) {
        wp_send_json_error( 'Missing parameters' );
    }
    
    // settings_raw is array if sent via complex ajax, or need handling?
    // jQuery ajax data object usually passes as array in PHP $_POST if we set it right.
    // Let's assume it's an array.Sanitize it.
    // We can use a recursive sanitize or just trust known keys.
    // For storing in JSON, we want to keep structure.
    
    $settings = array_map( 'sanitize_text_field', $settings_raw ); // Simple flat sanitization
    // Fix numeric types if needed later, but text is fine for JSON
    
    // Load Current Config (Merge with DB logic)
    $config = cafi_get_templates();
    
    // Find and Update
    $found = false;
    foreach ( $config as $index => $item ) {
        if ( $item['id'] === $template_id ) {
            // Ensure 'settings' key exists
            if (!isset($config[$index]['settings'])) {
                $config[$index]['settings'] = [];
            }
            
            // Merge valid keys
            $valid_keys = ['font_family', 'font_weight', 'font_size', 'font_color', 'text_position', 'text_alignment', 'padding_top', 'padding_bottom', 'padding_left', 'padding_right', 'logo_position', 'logo_offset_x', 'logo_offset_y', 'logo_size'];
            
            foreach ($settings as $k => $v) {
                if (in_array($k, $valid_keys)) {
                    $config[$index]['settings'][$k] = $v;
                }
            }
            
            $found = true;
            break;
        }
    }
    
    if ( ! $found ) {
        wp_send_json_error( 'Template ID not found' );
    }
    
    // Save to DB
    if ( update_option( 'cafi_templates_config', $config ) ) {
        wp_send_json_success( 'Settings saved to template successfully!' );
    } else {
        // Even if update_option returns false (no change), we can consider it success or just 'done'.
        // Sometimes it returns false if value is same.
        wp_send_json_success( 'Settings saved.' );
    }
}


// Legacy helper for backward compatibility/CSS inline styles


function cafi_options_page_html() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	
    // Include the Main Dashboard View
    require_once plugin_dir_path( __FILE__ ) . 'dashboard-main.php';
}
