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

/**
 * Map template key to a predefined color scheme (array of hex colors)
 */
function logindes_template_to_scheme($template_key)
{
    $map = array(
        'template1' => array('#0ea5e9', '#0369a1', '#f0f9ff'),
    );

    return isset($map[$template_key]) ? $map[$template_key] : $map['template1'];
}

/**
 * Handle saving template
 */
add_action('wp_ajax_logindes_save_template', 'logindes_handle_save_template');
add_action('wp_ajax_nopriv_logindes_save_template', 'logindes_handle_save_template');
function logindes_handle_save_template()
{
    if (!current_user_can('manage_options')) {
        wp_send_json_error([
            'message' => esc_html__('You do not have permission.', 'login-screen-designer'),
        ]);
    }

    $nonce = isset($_POST['logindes_nonce']) ? sanitize_text_field(wp_unslash($_POST['logindes_nonce'])) : '';
    if (!$nonce || !wp_verify_nonce($nonce, 'logindes_save_template')) {
        wp_send_json_error([
            'message' => esc_html__('Nonce verification failed.', 'login-screen-designer'),
        ]);
    }

    $template = isset($_POST['logindes_template']) ? sanitize_text_field(wp_unslash($_POST['logindes_template'])) : 'template1';

    update_option('logindes_selected_template', $template);
    update_option('logindes_color_scheme', logindes_template_to_scheme($template));

    wp_send_json_success([
        'message' => 'Template saved successfully',
    ]);
    exit;
}

/**
 *  Save logo Section
 */
add_action('wp_ajax_logindes_save_logo', 'logindes_handle_save_logo');
add_action('wp_ajax_nopriv_logindes_save_logo', 'logindes_handle_save_logo');
function logindes_handle_save_logo()
{
    if (!current_user_can('manage_options')) {
        wp_send_json_error([
            'message' => esc_html__('You do not have permission.', 'login-screen-designer'),
        ]);
    }

    $nonce = isset($_POST['logindes_logo_nonce']) ? sanitize_text_field(wp_unslash($_POST['logindes_logo_nonce'])) : '';
    if (!$nonce || !wp_verify_nonce($nonce, 'logindes_save_logo')) {
        wp_send_json_error([
            'message' => esc_html__('Nonce verification failed.', 'login-screen-designer'),
        ]);
    }

    $logo_url = isset($_POST['logindes_logo_url']) ? esc_url_raw(wp_unslash($_POST['logindes_logo_url'])) : '';
    $logo_text = isset($_POST['logindes_logo_text']) ? sanitize_text_field(wp_unslash($_POST['logindes_logo_text'])) : '';

    // Clear current logo if requested
    $logo_clear = isset($_POST['logindes_logo_clear']) ? sanitize_text_field(wp_unslash($_POST['logindes_logo_clear'])) : '';
    if ('1' === $logo_clear || !empty($logo_clear)) {
        delete_option('logindes_logo_url');
        delete_option('logindes_logo_attachment_id');
        $logo_url = '';
        $logo_text = '';
    }



    // Save Logo from media uploader URL
    if (!empty($_POST['logindes_logo_file'])) {
        $logo_url = esc_url_raw(wp_unslash($_POST['logindes_logo_file']));

        // Optional: get attachment ID from URL
        $attachment_id = attachment_url_to_postid($logo_url);

        update_option('logindes_logo_url', $logo_url);

        if ($attachment_id) {
            update_option('logindes_logo_attachment_id', (int) $attachment_id);
        }
    }

    // Numeric fields
    $fields_numeric = array(
        'logindes_logo_width',
        'logindes_logo_height',
        'logindes_logo_top',
        'logindes_logo_bottom',
        'logindes_logo_font_size',
        'logindes_logo_font_weight',
    );
    foreach ($fields_numeric as $f) {
        if (isset($_POST[$f])) {
            $val = intval(wp_unslash($_POST[$f]));
            update_option($f, $val);
        }
    }

    // String fields
    $fields_string = array(
        'logindes_logo_align', // left, center, right
        'logindes_logo_text_align',
        'logindes_logo_text_color',
    );
    foreach ($fields_string as $f) {
        if (isset($_POST[$f])) {
            $val = sanitize_text_field(wp_unslash($_POST[$f]));
            update_option($f, $val);
        }
    }

    // Explicitly update logo text and url if provided (already sanitized above)
    if (isset($_POST['logindes_logo_text'])) {
        update_option('logindes_logo_text', sanitize_text_field(wp_unslash($_POST['logindes_logo_text'])));
    }

    if (empty($logo_url) && isset($_POST['logindes_logo_url'])) {
        update_option('logindes_logo_url', esc_url_raw(wp_unslash($_POST['logindes_logo_url'])));
    }

    wp_send_json_success([
        'message' => 'Logo saved successfully',
    ]);
    exit;
}



/**
 * Save Background Section
 */
// add_action( 'wp_ajax_logindes_save_background', 'handle_save_background' );
add_action('wp_ajax_logindes_save_background', 'handle_save_background');
add_action('wp_ajax_nopriv_logindes_save_background', 'handle_save_background');
function handle_save_background()
{
    if (!current_user_can('manage_options')) {
        wp_send_json_error([
            'message' => esc_html__('You do not have permission.', 'login-screen-designer'),
        ]);
    }

    $nonce = isset($_POST['logindes_bg_nonce']) ? sanitize_text_field(wp_unslash($_POST['logindes_bg_nonce'])) : '';
    if (!$nonce || !wp_verify_nonce($nonce, 'logindes_save_background')) {
        wp_send_json_error([
            'message' => esc_html__('Nonce verification failed.', 'login-screen-designer'),
        ]);
    }

    // Remove background if requested
    $bg_clear = isset($_POST['logindes_bg_clear']) ? sanitize_text_field(wp_unslash($_POST['logindes_bg_clear'])) : '';
    if ('1' === $bg_clear || 'true' === $bg_clear) {
        delete_option('logindes_login_bg_image');
        delete_option('logindes_bg_attachment_id');
    }

    // Save background from media uploader URL
    if (!empty($_POST['logindes_bg_file'])) {
        $bg_url = esc_url_raw(wp_unslash($_POST['logindes_bg_file']));

        // Get attachment ID from URL (optional)
        $attachment_id = attachment_url_to_postid($bg_url);

        update_option('logindes_login_bg_image', $bg_url);

        if ($attachment_id) {
            update_option('logindes_bg_attachment_id', (int) $attachment_id);
        }
    }

    // Save other fields
    $fields = array(
        'logindes_login_bg_color',
        'logindes_login_bg_size_w',
        'logindes_login_bg_size_h',
        'logindes_login_bg_repeat',
        'logindes_login_bg_opacity',
        'logindes_login_bg_pos_left',
        'logindes_login_bg_pos_top',
        'logindes_login_bg_pos_bottom',
        'logindes_login_bg_pos_right',
        'logindes_login_bg_size_w_attr',
        'logindes_login_bg_size_h_attr',
        'logindes_login_padding_attr',
        'logindes_backgroundImagePosition',
    );

    foreach ($fields as $f) {

        if ( $f == 'logindes_login_bg_color' ) {
            $value = isset($_POST[$f]) ? sanitize_text_field(wp_unslash($_POST[$f])) : '';
            var_dump( $value );
        }

        $value = isset($_POST[$f]) ? sanitize_text_field(wp_unslash($_POST[$f])) : '';
        update_option($f, $value);
    }

    wp_send_json_success([
        'message' => 'Background saved successfully',
    ]);
    exit;
}

/**
 * Save Form Section
 */
add_action('wp_ajax_logindes_save_form', 'handle_save_form');
add_action('wp_ajax_nopriv_logindes_save_form', 'handle_save_form');
function handle_save_form()
{
    if (!current_user_can('manage_options')) {
        wp_send_json_error([
            'message' => esc_html__('You do not have permission.', 'login-screen-designer'),
        ]);
    }

    $nonce = isset($_POST['logindes_form_nonce']) ? sanitize_text_field(wp_unslash($_POST['logindes_form_nonce'])) : '';
    if (!$nonce || !wp_verify_nonce($nonce, 'logindes_save_form')) {
        wp_send_json_error([
            'message' => esc_html__('Nonce verification failed.', 'login-screen-designer'),
        ]);
    }

    $form_bg_clear = isset($_POST['logindes_form_bg_clear']) ? sanitize_text_field(wp_unslash($_POST['logindes_form_bg_clear'])) : '';
    if ('1' === $form_bg_clear || 'true' === $form_bg_clear) {
        delete_option('logindes_form_bg_image');
    }

    // Save Form Background from media uploader URL
    if (!empty($_POST['logindes_form_bg_file'])) {
        $form_bg_url = esc_url_raw(wp_unslash($_POST['logindes_form_bg_file']));

        // Optional: Get attachment ID from URL
        $attachment_id = attachment_url_to_postid($form_bg_url);

        update_option('logindes_form_bg_image', $form_bg_url);

        if ($attachment_id) {
            update_option('logindes_form_bg_attachment_id', (int) $attachment_id);
        }
    }

    // Save other fields
    $fields = array(
        'logindes_form_bg_color',
        'logindes_form_bg_transparent',
        'logindes_form_bg_width',
        'logindes_form_bg_size_width',
        'logindes_form_bg_height',
        'logindes_form_bg_size_height',
        'logindes_form_bg_repeat',
        'logindes_form_bg_opacity',
        'logindes_form_bg_position_top',
        'logindes_form_bg_position_bottom',
        'logindes_form_bg_position_left',
        'logindes_form_bg_position_right',
        'logindes_form_bg_w_attr',
        'logindes_form_bg_h_attr',
        'logindes_form_bg_size_width_attr',
        'logindes_form_bg_size_h_attr',
        'logindes_form_bg_padding_attr',
        'logindes_formBackgroundImagePosition',
    );

    foreach ($fields as $f) {
        $value = isset($_POST[$f]) ? sanitize_text_field(wp_unslash($_POST[$f])) : '';
        update_option($f, $value);
    }

    wp_send_json_success([
        'message' => 'Form saved successfully',
    ]);
    exit;
}

/**
 * Save Input Section
 */
add_action('wp_ajax_logindes_save_input', 'handle_save_input');
add_action('wp_ajax_nopriv_logindes_save_input', 'handle_save_input');
function handle_save_input()
{
    if (!current_user_can('manage_options')) {
        wp_send_json_error([
            'message' => esc_html__('You do not have permission.', 'login-screen-designer'),
        ]);
    }

    $nonce = isset($_POST['logindes_form_nonce']) ? sanitize_text_field(wp_unslash($_POST['logindes_form_nonce'])) : '';
    if (!$nonce || !wp_verify_nonce($nonce, 'logindes_save_input')) {
        wp_send_json_error([
            'message' => esc_html__('Nonce verification failed.', 'login-screen-designer'),
        ]);
    }

    // Save other fields
    $fields = array(
        'logindes_input_bg_color',
        'logindes_input_text_color',
        'logindes_input_font_size',
        'logindes_input_padding_top',
        'logindes_input_padding_bottom',
        'logindes_input_padding_left',
        'logindes_input_padding_right',
        'logindes_input_border_radius',
        'logindes_input_border_width',
        'logindes_input_border_style',
        'logindes_input_border_color',
        'logindes_input_font_size_attr',
        'logindes_input_padding_attr',
        'logindes_input_border_radius_attr',
        'logindes_input_border_width_attr',
    );

    foreach ($fields as $f) {
        $value = isset($_POST[$f]) ? sanitize_text_field(wp_unslash($_POST[$f])) : '';
        update_option($f, $value);
    }

    wp_send_json_success([
        'message' => 'Inputs saved successfully',
    ]);
    exit;
}

/**
 * Save Button Section
 */
add_action('wp_ajax_logindes_save_button', 'handle_save_button');
add_action('wp_ajax_nopriv_logindes_save_button', 'handle_save_button');
function handle_save_button()
{
    if (!current_user_can('manage_options')) {
        wp_send_json_error([
            'message' => esc_html__('You do not have permission.', 'login-screen-designer'),
        ]);
    }

    $nonce = isset($_POST['logindes_form_nonce']) ? sanitize_text_field(wp_unslash($_POST['logindes_form_nonce'])) : '';
    if (!$nonce || !wp_verify_nonce($nonce, 'logindes_save_button')) {
        wp_send_json_error([
            'message' => esc_html__('Nonce verification failed.', 'login-screen-designer'),
        ]);
    }

    // Save other fields
    $fields = array(
        'logindes_button_bg_color',
        'logindes_button_text_color',
        'logindes_button_font_size',
        'logindes_button_padding_top',
        'logindes_button_padding_bottom',
        'logindes_button_padding_left',
        'logindes_button_padding_right',
        'logindes_button_border_radius',
        'logindes_button_border_width',
        'logindes_button_border_style',
        'logindes_button_border_color',
        'logindes_button_font_size_attr',
        'logindes_button_padding_attr',
        'logindes_button_border_radius_attr',
        'logindes_button_border_width_attr',
        
    );

    foreach ($fields as $f) {
        $value = isset($_POST[$f]) ? sanitize_text_field(wp_unslash($_POST[$f])) : '';
        update_option($f, $value);
    }

    wp_send_json_success([
        'message' => 'Buttons saved successfully',
    ]);
    exit;
}

/**
 * Save Label Section
 */
add_action('wp_ajax_logindes_save_label', 'handle_save_label');
add_action('wp_ajax_nopriv_logindes_save_label', 'handle_save_label');
function handle_save_label()
{
    if (!current_user_can('manage_options')) {
        wp_send_json_error([
            'message' => esc_html__('You do not have permission.', 'login-screen-designer'),
        ]);
    }

    $nonce = isset($_POST['logindes_form_nonce']) ? sanitize_text_field(wp_unslash($_POST['logindes_form_nonce'])) : '';
    if (!$nonce || !wp_verify_nonce($nonce, 'logindes_save_label')) {
        wp_send_json_error([
            'message' => esc_html__('Nonce verification failed.', 'login-screen-designer'),
        ]);
    }

    // Save other fields
    $fields = array(
        'logindes_label_text_color',
        'logindes_label_font_size',
        'logindes_forgot_font_size',
        'logindes_forgot_text_color',
        'logindes_label_font_size_attr',
        'logindes_forgot_font_size_attr',
    );

    foreach ($fields as $f) {
        $value = isset($_POST[$f]) ? sanitize_text_field(wp_unslash($_POST[$f])) : '';
        update_option($f, $value);
    }

    wp_send_json_success([
        'message' => 'Label saved successfully',
    ]);
    exit;
}