<?php
/**
 * LVMR – Customizer: Brand Color Settings
 *
 * Registers a "LVMR Brand Colors" panel in Appearance → Customize with
 * two color pickers (Accent Lime + Primary Green). The chosen colors are
 * output as CSS custom-property overrides in <head> on every page that
 * loads the plugin's stylesheets, so every WooCommerce page updates instantly.
 */

if ( ! defined( 'ABSPATH' ) ) { exit; }

/* ── Defaults ─────────────────────────────────────────────────── */
define( 'LVMR_DEFAULT_LIME',  '#C7DC49' );
define( 'LVMR_DEFAULT_GREEN', '#224E2F' );

/* ════════════════════════════════════════════════════════════════
   1.  Register Customizer panel, section, settings & controls
   ════════════════════════════════════════════════════════════════ */
add_action( 'customize_register', 'lvmr_customizer_register' );

function lvmr_customizer_register( $wp_customize ) {

    /* ── Panel ──────────────────────────────────────────────── */
    $wp_customize->add_panel( 'lvmr_brand_panel', [
        'title'       => __( '🌿 LVMR Brand Colors', 'lvmr-product-page' ),
        'description' => __( 'Change the two global brand colors used across all WooCommerce pages (cart, checkout, account, product page, shop archive, etc.).', 'lvmr-product-page' ),
        'priority'    => 30,
    ] );

    /* ── Section ────────────────────────────────────────────── */
    $wp_customize->add_section( 'lvmr_colors_section', [
        'title'    => __( 'Brand Colors', 'lvmr-product-page' ),
        'panel'    => 'lvmr_brand_panel',
        'priority' => 10,
    ] );

    /* ── Setting: Accent / Lime color ───────────────────────── */
    $wp_customize->add_setting( 'lvmr_color_lime', [
        'default'           => LVMR_DEFAULT_LIME,
        'type'              => 'option',
        'capability'        => 'edit_theme_options',
        'sanitize_callback' => 'sanitize_hex_color',
        'transport'         => 'postMessage',   // live preview
    ] );

    $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'lvmr_color_lime', [
        'label'       => __( 'Accent Color (Lime)', 'lvmr-product-page' ),
        'description' => __( 'Used for buttons, badges, highlights and the zoom lens. Default: #C7DC49', 'lvmr-product-page' ),
        'section'     => 'lvmr_colors_section',
        'priority'    => 10,
    ] ) );

    /* ── Setting: Primary / Green color ─────────────────────── */
    $wp_customize->add_setting( 'lvmr_color_green', [
        'default'           => LVMR_DEFAULT_GREEN,
        'type'              => 'option',
        'capability'        => 'edit_theme_options',
        'sanitize_callback' => 'sanitize_hex_color',
        'transport'         => 'postMessage',
    ] );

    $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'lvmr_color_green', [
        'label'       => __( 'Primary Color (Green)', 'lvmr-product-page' ),
        'description' => __( 'Used for text, table headers, navigation, and dark backgrounds. Default: #224E2F', 'lvmr-product-page' ),
        'section'     => 'lvmr_colors_section',
        'priority'    => 20,
    ] ) );

    /* ── Section: Pickup Location ────────────────────────────── */
    $wp_customize->add_section( 'lvmr_pickup_section', [
        'title'    => __( 'Pickup Location', 'lvmr-product-page' ),
        'panel'    => 'lvmr_brand_panel',
        'priority' => 20,
    ] );

    /* ── Setting: Pickup Address ────────────────────────────── */
    $wp_customize->add_setting( 'lvmr_pickup_location', [
        'default'           => '',
        'type'              => 'option',
        'capability'        => 'edit_theme_options',
        'sanitize_callback' => 'sanitize_text_field',
    ] );

    $wp_customize->add_control( 'lvmr_pickup_location', [
        'label'       => __( 'Pickup Location Address', 'lvmr-product-page' ),
        'description' => __( 'Enter the pickup location to display on the product page. Leave blank to hide.', 'lvmr-product-page' ),
        'section'     => 'lvmr_pickup_section',
        'type'        => 'text',
        'priority'    => 10,
    ] );
}

/* ════════════════════════════════════════════════════════════════
   2.  Color helpers – derive tints & shades from a hex color
   ════════════════════════════════════════════════════════════════ */

/**
 * Parse a CSS hex color to [r, g, b].
 */
function lvmr_hex_to_rgb( $hex ) {
    $hex = ltrim( $hex, '#' );
    if ( strlen( $hex ) === 3 ) {
        $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
    }
    return [
        'r' => hexdec( substr( $hex, 0, 2 ) ),
        'g' => hexdec( substr( $hex, 2, 2 ) ),
        'b' => hexdec( substr( $hex, 4, 2 ) ),
    ];
}

/**
 * Mix a hex color with white (positive $pct) or black (negative) by $pct%.
 * $pct 0–100: % toward white; -100–0: % toward black.
 */
function lvmr_color_mix( $hex, $pct ) {
    $rgb    = lvmr_hex_to_rgb( $hex );
    $target = $pct > 0 ? 255 : 0;   // white or black
    $pct    = abs( $pct ) / 100;

    $r = (int) round( $rgb['r'] + ( $target - $rgb['r'] ) * $pct );
    $g = (int) round( $rgb['g'] + ( $target - $rgb['g'] ) * $pct );
    $b = (int) round( $rgb['b'] + ( $target - $rgb['b'] ) * $pct );

    return sprintf( '#%02x%02x%02x', $r, $g, $b );
}

/**
 * Convert hex to rgba() string.
 */
function lvmr_hex_rgba( $hex, $alpha ) {
    $rgb = lvmr_hex_to_rgb( $hex );
    return "rgba({$rgb['r']},{$rgb['g']},{$rgb['b']},$alpha)";
}

/* ════════════════════════════════════════════════════════════════
   3.  Output inline CSS custom properties to <head>
       Runs on both front-end render and Customizer preview iframe.
   ════════════════════════════════════════════════════════════════ */
add_action( 'wp_head', 'lvmr_output_brand_css_vars', 5 );

function lvmr_output_brand_css_vars() {
    $lime  = sanitize_hex_color( get_option( 'lvmr_color_lime',  LVMR_DEFAULT_LIME  ) ) ?: LVMR_DEFAULT_LIME;
    $green = sanitize_hex_color( get_option( 'lvmr_color_green', LVMR_DEFAULT_GREEN ) ) ?: LVMR_DEFAULT_GREEN;

    // Derived tints / shades
    $lime_dark   = lvmr_color_mix( $lime,  -12 );   // slightly darker lime
    $lime_light  = lvmr_color_mix( $lime,   82 );   // very pale lime tint
    $green_mid   = lvmr_color_mix( $green,  18 );   // slightly lighter green
    $green_light = lvmr_color_mix( $green,  90 );   // near-white green tint

    // RGBA versions for shadows / overlays
    $lime_shadow  = lvmr_hex_rgba( $lime,  '0.35' );
    $green_shadow = lvmr_hex_rgba( $green, '0.28' );
    $lime_overlay = lvmr_hex_rgba( $lime,  '0.15' );
    $lime_badge   = lvmr_hex_rgba( $lime,  '0.85' );

    // Only output if colors differ from defaults OR always output for Customizer
    echo "\n<style id=\"lvmr-brand-vars\">\n:root {\n";

    // ── Product page variables (--pp-*) ──────────────────────
    echo "  --pp-lime:         {$lime};\n";
    echo "  --pp-lime-dark:    {$lime_dark};\n";
    echo "  --pp-lime-light:   {$lime_light};\n";
    echo "  --pp-green:        {$green};\n";
    echo "  --pp-green-mid:    {$green_mid};\n";
    echo "  --pp-green-light:  {$green_light};\n";

    // ── WooCommerce global variables (--wg-*) ────────────────
    echo "  --wg-lime:         {$lime};\n";
    echo "  --wg-lime-dark:    {$lime_dark};\n";
    echo "  --wg-lime-light:   {$lime_light};\n";
    echo "  --wg-green:        {$green};\n";
    echo "  --wg-green-mid:    {$green_mid};\n";
    echo "  --wg-green-light:  {$green_light};\n";

    echo "}\n</style>\n";
}

/* ════════════════════════════════════════════════════════════════
   4.  Live Preview – postMessage JS
       Updates CSS vars in the Customizer iframe without a full
       page reload (works because both CSS files use :root vars).
   ════════════════════════════════════════════════════════════════ */
add_action( 'customize_preview_init', 'lvmr_customizer_preview_js' );

function lvmr_customizer_preview_js() {
    wp_add_inline_script( 'customize-preview', "
( function( $ ) {
    'use strict';

    /**
     * Recalculate and inject derived vars whenever a color picker changes.
     */
    function applyColors( lime, green ) {
        var style = document.getElementById('lvmr-brand-vars');
        if ( ! style ) {
            style = document.createElement('style');
            style.id = 'lvmr-brand-vars';
            document.head.appendChild( style );
        }

        // Simple JS tint helpers (mirrors PHP lvmr_color_mix)
        function mix( hex, pct ) {
            hex = hex.replace('#','');
            if ( hex.length === 3 ) hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
            var r = parseInt(hex.substr(0,2),16),
                g = parseInt(hex.substr(2,2),16),
                b = parseInt(hex.substr(4,2),16),
                t = pct > 0 ? 255 : 0,
                p = Math.abs(pct)/100;
            r = Math.round( r + (t-r)*p );
            g = Math.round( g + (t-g)*p );
            b = Math.round( b + (t-b)*p );
            return '#'+[r,g,b].map(function(v){return ('0'+v.toString(16)).slice(-2);}).join('');
        }

        var limeDark   = mix( lime,  -12 );
        var limeLight  = mix( lime,   82 );
        var greenMid   = mix( green,  18 );
        var greenLight = mix( green,  90 );

        var css = ':root {\\n'
            + '  --pp-lime: '        + lime       + ';\\n'
            + '  --pp-lime-dark: '   + limeDark   + ';\\n'
            + '  --pp-lime-light: '  + limeLight  + ';\\n'
            + '  --pp-green: '       + green      + ';\\n'
            + '  --pp-green-mid: '   + greenMid   + ';\\n'
            + '  --pp-green-light: ' + greenLight + ';\\n'
            + '  --wg-lime: '        + lime       + ';\\n'
            + '  --wg-lime-dark: '   + limeDark   + ';\\n'
            + '  --wg-lime-light: '  + limeLight  + ';\\n'
            + '  --wg-green: '       + green      + ';\\n'
            + '  --wg-green-mid: '   + greenMid   + ';\\n'
            + '  --wg-green-light: ' + greenLight + ';\\n'
            + '}';

        style.textContent = css;
    }

    // Store current values
    var currentLime  = wp.customize( 'lvmr_color_lime'  )();
    var currentGreen = wp.customize( 'lvmr_color_green' )();

    // Watch lime
    wp.customize( 'lvmr_color_lime', function( value ) {
        value.bind( function( newLime ) {
            currentLime = newLime;
            applyColors( currentLime, currentGreen );
        } );
    } );

    // Watch green
    wp.customize( 'lvmr_color_green', function( value ) {
        value.bind( function( newGreen ) {
            currentGreen = newGreen;
            applyColors( currentLime, currentGreen );
        } );
    } );

} )( jQuery );
" );
}
