<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

/**
 * PT Piano Plugin Functions
 */

// Note: PTPIAN_PLUGIN_URL and PTPIAN_PLUGIN_DIR are defined in ptpiano.php


/**
 * Add admin menu for PT Piano settings
 */
function ptpian_admin_menu() {
    $icon = PTPIAN_PLUGIN_URL . "icon.png";
    add_menu_page(
        'PT Piano',
        'PT Piano',
        'manage_options',
        'ptpian_settings',
        'ptpian_render_settings_page',
        $icon
    );   
}
add_action('admin_menu', 'ptpian_admin_menu');

/**
 * Enqueue Admin scripts and styles
 */

add_action('admin_enqueue_scripts', 'ptpian_enqueue_admin_assets');

function ptpian_enqueue_admin_assets($hook) {
    // Only load on our settings page
    if ($hook !== 'toplevel_page_ptpian_settings') {
        return;
    }

    wp_enqueue_style(
        'ptpian-admin-style',
        PTPIAN_PLUGIN_URL . 'styles/admin-settings.css',
        array(),
        '1.2.5'
    );

    wp_enqueue_script(
        'ptpian-admin-script',
        PTPIAN_PLUGIN_URL . 'js/admin-settings.js',
        array(),
        '1.2.5',
        true
    );
}

/**
 * Enqueue frontend scripts and styles
 */
add_action('wp_enqueue_scripts', 'ptpian_enqueue_assets');

function ptpian_enqueue_assets() {	
	
     if ( is_admin() || !is_singular() ) {
        return;
    }

    global $post;

	if ( !has_shortcode( $post->post_content, 'PT-Piano' ) && !has_shortcode( $post->post_content, '[PT-Piano]' ) && !has_shortcode( $post->post_content, 'pt-piano' ) && strpos( $post->post_content, '[PT-Piano' ) !== false) {
		return;
	}

	
    // CSS
    wp_enqueue_style(
        'ptpian-style',
        PTPIAN_PLUGIN_URL . 'styles/piano.css',
        array(),
        '1.3.7',
        'all'
    );
	
	wp_enqueue_style(
		'ptpian-dynamic-style',
		PTPIAN_PLUGIN_URL . 'styles/frontend-dynamic.css',
		array(),
		'1.2.5',
		'all'
	);
	
	// Set dynamic CSS variables
    $css_vars = ':root {';
	$css_vars .= '--ptpian-control-bg-color: ' . esc_attr(get_option('ptpian_bgcolor_control')) . ';';
    $css_vars .= '--ptpian-control-toggle-color: ' . esc_attr(get_option('ptpian_toggle_control')) . ';';
	$css_vars .= '--ptpian-control-select-color: ' . esc_attr(get_option('ptpian_select_control')) . ';';
    $css_vars .= '--ptpian-txt-piano-color: ' . esc_attr(get_option('ptpian_txtcolor_piano')) . ';';
    $css_vars .= '--ptpian-mark-bg-color: ' . esc_attr(get_option('ptpian_markcolor_piano')) . ';';
    $css_vars .= '--ptpian-mark-text-color: ' . esc_attr(get_option('ptpian_txtcolor_piano')) . ';';
    
    // Handle background image
    $theme = get_option('ptpian_theme') ?: 'default-theme.png';
    $bg_url = esc_url(PTPIAN_PLUGIN_URL . "theme/" . $theme);
    $css_vars .= '--ptpian-theme-bg: url("' . $bg_url . '");';
	
	// Set key highlights color
	$keylight_color = get_option('ptpian_keylights_color');
	$css_vars .= '--ptpian-keylight-color: ' . esc_attr($keylight_color) . ';';

    $css_vars .= '}';

    wp_add_inline_style('ptpian-dynamic-style', $css_vars);


    /* JS - piano sound
    wp_register_script(
        'ptpian-sound',
        PTPIAN_PLUGIN_URL . 'js/piano.sound.js',
        array(),
        '1.2.5',
        true
    );*/
	
	wp_register_script(
		'ptpian-sound',
		PTPIAN_PLUGIN_URL . 'js/piano.sound.js',
		array('ptpian-recorder'), // ✅ recorder must load first
		'1.2.5',
		true
	);


    wp_enqueue_script('ptpian-sound');
	
	// JS - Control
    wp_enqueue_script(
        'control',
        PTPIAN_PLUGIN_URL . 'js/control.js',
        array(),
        '1.3.7',
        true
    );
	
	// JS - chords and scales unified
    wp_enqueue_script(
        'ptpian-chords-scales',
        PTPIAN_PLUGIN_URL . 'js/piano.chords-scales.js',
        array(),
        '1.3.7',
        true
    );
	
	// JS - Indian Raag scale visual track
    wp_enqueue_script(
        'ptpian-scale',
        PTPIAN_PLUGIN_URL . 'js/piano.scale.js',
        array(),
        '1.3.7',
        true
    );
	
	
	// - Settings ---
    wp_enqueue_script(
        'ptpian-settings',
        PTPIAN_PLUGIN_URL . 'js/piano.settings.pop.js', // create this file
        array(), // make sure sound is loaded first
        '1.3.7',
        true
    );
	
	
	// - WebAudioFont Player (CDN) ---
    wp_enqueue_script(
        'webaudiofont-player',
        'https://surikov.github.io/webaudiofont/npm/dist/WebAudioFontPlayer.js',
        array(),
        '3.0',
        true
    );

	// - SoundFont Engine ---
    wp_enqueue_script(
        'ptpian-soundfont',
        PTPIAN_PLUGIN_URL . 'js/piano.soundfont.js',
        array('webaudiofont-player'),
        '1.3.7',
        true
    );

	// - Reverb ---
    wp_enqueue_script(
        'ptpian-reverb',
        PTPIAN_PLUGIN_URL . 'js/piano.reverb.js', // create this file
        array('ptpian-sound'), // make sure sound is loaded first
        '1.3.7',
        true
    );
	
	// - Record ---	
		// Enqueue MidiWriterJS from CDN
	wp_enqueue_script(
		'midiwriter-js',
		PTPIAN_PLUGIN_URL . 'js/midiwriter.min.js', // include midi js file
		array(), // No dependencies
		'2.1.1',
		true // Load in footer
	);
   
	wp_enqueue_script('ptpian-recorder', plugin_dir_url(__FILE__) . 'js/piano.recorder.js', array(), '1.3.7', true);
	
	wp_add_inline_script('ptpian-sound', 'var ajaxurl = "' . esc_js(admin_url('admin-ajax.php')) . '";', 'before');


    // Localize IR files for reverb
    $ir_files = array(
        'hall'  => PTPIAN_PLUGIN_URL . 'ir/101-LargeHall.wav',
        'room'  => PTPIAN_PLUGIN_URL . 'ir/113-RoomAmb.wav',
        'plate' => PTPIAN_PLUGIN_URL . 'ir/109-CoolPlate.wav',
    );

    wp_localize_script('ptpian-reverb', 'ptpianReverbData', array(
        'irs' => $ir_files,
    ));
	
	// - MIDI Connect ---
    wp_enqueue_script(
        'ptpian-midi',
        PTPIAN_PLUGIN_URL . 'js/piano.web.midi.js', // create this file
        array('ptpian-sound'), // make sure sound is loaded first
        '1.2.5',
        true
    );
	
	// Pass PHP setting to JavaScript for Record duration
    $record_duration = get_option('ptpian_record_duration', 30); // Default: 30 seconds

    wp_localize_script('ptpian-sound', 'ptPianSettings', array(
        'recordDuration' => $record_duration
    ));
	
	// - SONG Connect ---
	wp_enqueue_script(
    'ptpian-songs',
    PTPIAN_PLUGIN_URL . 'js/piano.songs.note.js',
    array(), // dependency
    '1.0',
    true
	);
	// Localize Song files
	$songs = get_option('ptpian_songs_data', []);

	wp_localize_script('ptpian-songs', 'ptpianSongs', $songs);


}

/**
 * Register plugin settings
 */
 add_action('admin_init', 'ptpian_register_settings');
function ptpian_register_settings() {
	// Note name display option
	register_setting('ptpian_settings_group', 'ptpian_note_display', array(
		'type'              => 'string',
		'sanitize_callback' => 'sanitize_text_field',
		'default'           => 'letters',
	));

	// Chord toggle options
	register_setting('ptpian_settings_group', 'ptpian_chordtxt_switch', array(
		'type'              => 'string',
		'sanitize_callback' => 'ptpian_sanitize_checkbox',
		'default'           => '0',
	));
	register_setting('ptpian_settings_group', 'ptpian_chordmajor_switch', array(
		'type'              => 'string',
		'sanitize_callback' => 'ptpian_sanitize_checkbox',
		'default'           => '0',
	));
	register_setting('ptpian_settings_group', 'ptpian_chordminor_switch', array(
		'type'              => 'string',
		'sanitize_callback' => 'ptpian_sanitize_checkbox',
		'default'           => '0',
	));
	register_setting('ptpian_settings_group', 'ptpian_chorddim_switch', array(
		'type'              => 'string',
		'sanitize_callback' => 'ptpian_sanitize_checkbox',
		'default'           => '0',
	));
	register_setting('ptpian_settings_group', 'ptpian_chordagu_switch', array(
		'type'              => 'string',
		'sanitize_callback' => 'ptpian_sanitize_checkbox',
		'default'           => '0',
	));

	// Color settings
	register_setting('ptpian_settings_group', 'ptpian_bgcolor_control', array(
		'type'              => 'string',
		'sanitize_callback' => 'sanitize_hex_color',
		'default'           => '',
	));
	register_setting('ptpian_settings_group', 'ptpian_toggle_control', array(
		'type'              => 'string',
		'sanitize_callback' => 'sanitize_hex_color',
		'default'           => '',
	));
	register_setting('ptpian_settings_group', 'ptpian_select_control', array(
		'type'              => 'string',
		'sanitize_callback' => 'sanitize_hex_color',
		'default'           => '',
	));
	register_setting('ptpian_settings_group', 'ptpian_txtcolor_piano', array(
		'type'              => 'string',
		'sanitize_callback' => 'sanitize_hex_color',
		'default'           => '',
	));
	register_setting('ptpian_settings_group', 'ptpian_markcolor_piano', array(
		'type'              => 'string',
		'sanitize_callback' => 'sanitize_hex_color',
		'default'           => '',
	));

	// Theme option
	register_setting('ptpian_settings_group', 'ptpian_theme', array(
		'type'              => 'string',
		'sanitize_callback' => 'sanitize_text_field',
		'default'           => 'default-theme.png',
	));

	// Piano key lights color
	register_setting('ptpian_settings_group', 'ptpian_keylights_color', array(
		'type'              => 'string',
		'sanitize_callback' => 'sanitize_hex_color',
		'default'           => '',
	));

	// Recording duration (in seconds)
	register_setting('ptpian_settings_group', 'ptpian_record_duration', array(
		'type'              => 'integer',
		'sanitize_callback' => 'absint',
		'default'           => 30,
	));

	// 🎼 Song Library
	register_setting('ptpian_settings_group', 'ptpian_songs_data', array(
		'type'              => 'array',
		'sanitize_callback' => 'ptpian_sanitize_songs',
		'default'           => array(),
	));

}

/**
 * Checkbox sanitizer
 */
function ptpian_sanitize_checkbox($input) {
    return $input === '1' ? '1' : '0';
}

/**
 * Render settings page
 */
function ptpian_render_settings_page() {
    include_once(PTPIAN_PLUGIN_DIR . 'PT_Piano_Setting.php');
}

/**
 * Song sanitizer
 */
function ptpian_sanitize_songs($input) {
    $clean = [];

    if (!empty($input)) {
        foreach ($input as $song) {

            // skip empty rows
            if (empty($song['name']) && empty($song['notes'])) {
                continue;
            }

            $clean[] = [
                'name'  => sanitize_text_field($song['name']),
                'scale' => sanitize_text_field($song['scale']),
                'notes' => sanitize_text_field($song['notes']),
            ];
        }
    }

    return $clean;
}
?>