<?php


if (!function_exists('firefly_customizer_background_images')) {
    function firefly_customizer_background_images($wp_customize) {

        // Section
        $wp_customize->add_section('firefly_background_images_section', array(
            'title'    => __('Firefly Background Images', 'firefly'),
            'priority' => 30,
        ));

        // Background settings
        $backgrounds = [
            'page' => 'Page Background',
            'content' => 'Content Background',
        ];

        foreach ($backgrounds as $key => $label) {

            // Image
            $wp_customize->add_setting("firefly_bg_{$key}_image", [
                'default'           => '',
                'sanitize_callback' => 'esc_url_raw',
            ]);
            $wp_customize->add_control(new WP_Customize_Image_Control(
                $wp_customize,
                "firefly_bg_{$key}_image_control",
                [
                    'label'    => __("$label Image", 'firefly'),
                    'section'  => 'firefly_background_images_section',
                    'settings' => "firefly_bg_{$key}_image",
                ]
            ));

            // Display style
            $wp_customize->add_setting("firefly_bg_{$key}_style", [
                'default'           => 'cover',
                'sanitize_callback' => 'sanitize_text_field',
            ]);
            $wp_customize->add_control("firefly_bg_{$key}_style", [
                'label'   => __("$label Display Style", 'firefly'),
                'section' => 'firefly_background_images_section',
                'type'    => 'select',
                'choices' => [
                    'cover'      => 'Cover',
                    'contain'    => 'Contain',
                    'repeat'     => 'Tile (repeat)',
                    'no-repeat'  => 'No Repeat',
                    'center'     => 'Center',
                ],
            ]);
        }
    }

    add_action('customize_register', 'firefly_customizer_background_images');
}


function firefly_output_background_images_css() {
    $page_img    = get_theme_mod('firefly_bg_page_image');
    $page_style  = get_theme_mod('firefly_bg_page_style', 'cover');

    $content_img   = get_theme_mod('firefly_bg_content_image');
    $content_style = get_theme_mod('firefly_bg_content_style', 'cover');

    echo '<style>';

    if ($page_img) {
        echo "body { background-image: url('$page_img'); background-size: $page_style; background-repeat: " . ($page_style === 'repeat' ? 'repeat' : 'no-repeat') . "; background-position: center; }";
    }

    if ($content_img) {
        echo ".site { background-image: url('$content_img'); background-size: $content_style; background-repeat: " . ($content_style === 'repeat' ? 'repeat' : 'no-repeat') . "; background-position: center; }";
    }

    echo '</style>';
}
add_action('wp_head', 'firefly_output_background_images_css');
