<?php
/*
Theme Name: Blocksy Child
Template: blocksy
Version: 1.0.0
Description: Child theme for Blocksy
Author: Your Name
*/
/**
 * Blocksy Child – functions (cache-busted enqueues, safer editor preview)
 */

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

/* --------------------------------------------------------------------------
   Helpers
-------------------------------------------------------------------------- */

if (!function_exists('sek_file_ver')) {
	function sek_file_ver($abs_path, $fallback = null) {
		if (is_string($abs_path) && file_exists($abs_path)) {
			$mt = @filemtime($abs_path);
			if ($mt) return (string) $mt;
		}
		return $fallback ?: wp_get_theme(get_template())->get('Version');
	}
}

if (!function_exists('sek_hex_to_rgba')) {
	function sek_hex_to_rgba($hex, $alpha) {
		$hex = sanitize_hex_color($hex) ?: '#000000';
		$hex = ltrim($hex, '#');
		if (strlen($hex) === 3) $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
		$r = hexdec(substr($hex, 0, 2));
		$g = hexdec(substr($hex, 2, 2));
		$b = hexdec(substr($hex, 4, 2));
		$alpha = floatval($alpha);
		if ($alpha > 1) $alpha /= 100;
		$alpha = max(0, min(1, $alpha));
		return sprintf('rgba(%d,%d,%d,%.3f)', $r, $g, $b, $alpha);
	}
}

if (!function_exists('sek_resolve_media_url')) {
	function sek_resolve_media_url($raw, $type = 'image') {
		if (!$raw) return '';
		if (is_array($raw)) {
			if (!empty($raw['url']) && filter_var($raw['url'], FILTER_VALIDATE_URL)) return $raw['url'];
			if (isset($raw['ID']) || isset($raw['id'])) $raw = isset($raw['ID']) ? $raw['ID'] : $raw['id'];
		}
		if (is_numeric($raw)) {
			return ($type === 'image')
				? (wp_get_attachment_image_url((int) $raw, 'full') ?: '')
				: (wp_get_attachment_url((int) $raw) ?: '');
		}
		if (is_string($raw) && filter_var($raw, FILTER_VALIDATE_URL)) return $raw;
		return '';
	}
}

if (!function_exists('sek_video_mime_from_url')) {
	function sek_video_mime_from_url($url) {
		$ext = strtolower(pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION));
		return $ext === 'mp4' ? 'video/mp4'
			: ($ext === 'webm' ? 'video/webm'
			: (($ext === 'ogv' || $ext === 'ogg') ? 'video/ogg' : ''));
	}
}

/* --------------------------------------------------------------------------
   Enqueues (run very late so our overrides win)
-------------------------------------------------------------------------- */
add_action('wp_enqueue_scripts', function () {
	$theme_ver = wp_get_theme(get_template())->get('Version');

	// Parent CSS
	wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css', [], $theme_ver);

	// Child CSS (mtime version + proper deps)
	$child_handle = 'child-style';
	$child_path   = get_stylesheet_directory() . '/style.css';
	$child_uri    = get_stylesheet_uri();
	$child_ver    = sek_file_ver($child_path, $theme_ver);

	$deps = ['parent-style'];
	foreach (['blocksy-styles','ct-main'] as $blocksy_handle) {
		if (wp_style_is($blocksy_handle, 'registered') || wp_style_is($blocksy_handle, 'enqueued')) {
			$deps[] = $blocksy_handle; break;
		}
	}
	if (wp_style_is('elementor-frontend', 'registered') || wp_style_is('elementor-frontend', 'enqueued')) {
		$deps[] = 'elementor-frontend';
	}

	if (wp_style_is($child_handle, 'enqueued') || wp_style_is($child_handle, 'registered')) {
		wp_dequeue_style($child_handle);
		wp_deregister_style($child_handle);
	}
	wp_register_style($child_handle, $child_uri, $deps, $child_ver);
	wp_enqueue_style($child_handle);

	// Accordion CSS (kill legacy handles, then enqueue ours)
	foreach (['accordion-style','sek-accordion-style','sek-elementor-accordion','sek-elementor-accordion-v2','sek-acc-v3'] as $h) {
		if (wp_style_is($h, 'enqueued') || wp_style_is($h, 'registered')) { wp_dequeue_style($h); wp_deregister_style($h); }
	}
	$acc_rel  = 'css/accordion-elementor.v3.css';
	$acc_path = trailingslashit(get_stylesheet_directory()) . $acc_rel;
	$acc_uri  = trailingslashit(get_stylesheet_directory_uri()) . $acc_rel;
	$acc_ver  = sek_file_ver($acc_path, $theme_ver);
	if (file_exists($acc_path)) {
		wp_register_style('sek-acc-v3', $acc_uri, [$child_handle], $acc_ver);
		wp_enqueue_style('sek-acc-v3');
	}

	// Child JS (mtime + defer)
	$js_rel  = 'js/menu.js';
	$js_path = trailingslashit(get_stylesheet_directory()) . $js_rel;
	$js_uri  = trailingslashit(get_stylesheet_directory_uri()) . $js_rel;
	$js_ver  = sek_file_ver($js_path, $theme_ver);
	wp_enqueue_script('blocksy-child-menu', $js_uri, ['jquery'], $js_ver, true);
	if (function_exists('wp_script_add_data')) wp_script_add_data('blocksy-child-menu', 'strategy', 'defer');

	/* Inline CSS tokens for overlay/video (attach to child-style; no echo) */
	$inline_css = '
		.site-bg-video{position:fixed;inset:0;width:100%;height:100%;object-fit:cover;pointer-events:none;z-index:0;}
		@media (max-width:1024px){.site-bg-video[data-disable-on-mobile="true"]{display:none}}
		.site-overlay{position:fixed;inset:0;background:var(--overlay-color, rgba(0,0,0,.5));pointer-events:none;z-index:1;display:block!important;}
		#header,#footer,#main-container{position:relative;z-index:2;}
	';

	$g_enable  = (bool) get_theme_mod('sek_overlay_global_enable', true);
	$g_hex     = get_theme_mod('sek_overlay_global_color', '#000000');
	$g_opacity = get_theme_mod('sek_overlay_global_opacity', 0.5);
	$g_rgba    = sek_hex_to_rgba($g_hex, $g_opacity);

	if (!is_page()) {
		$inline_css .= $g_enable ? sprintf(':root{--overlay-color:%s}', $g_rgba) : '.site-overlay{display:none!important}';
		wp_add_inline_style($child_handle, $inline_css);
		return;
	}

	$post_id = get_queried_object_id();
	if ($post_id) {
		$p_enable  = get_post_meta($post_id, 'sek_overlay_enable', true);   // ''(inherit) | 0 | 1
		$p_color   = get_post_meta($post_id, 'sek_overlay_color', true);    // hex
		$p_opacity = get_post_meta($post_id, 'sek_overlay_opacity', true);  // 0..1 or 0..100

		if ($p_enable !== '' && (int) $p_enable === 0) {
			$inline_css .= sprintf('.page-id-%d .site-overlay{display:none!important}', (int) $post_id);
		} else {
			$use_enable = ($p_enable === '' ? $g_enable : (bool) $p_enable);
			if (!$use_enable) {
				$inline_css .= sprintf('.page-id-%d .site-overlay{display:none!important}', (int) $post_id);
			} else {
				$use_hex   = $p_color   ?: $g_hex;
				$use_alpha = ($p_opacity === '' ? $g_opacity : $p_opacity);
				$use_rgba  = sek_hex_to_rgba($use_hex, $use_alpha);
				$inline_css .= sprintf('.page-id-%d{--overlay-color:%s}', (int) $post_id, $use_rgba);
			}
		}

		$bg_raw = get_post_meta($post_id, 'sek_bg_image', true);
		$bg_url = sek_resolve_media_url($bg_raw, 'image');
		if ($bg_url) {
			$inline_css .= sprintf(
				'body.page-id-%1$d{background-image:url("%2$s")!important;background-size:cover;background-repeat:no-repeat;background-position:center center;background-attachment:scroll;}',
				(int) $post_id,
				esc_url($bg_url)
			);
		}
	}
	wp_add_inline_style($child_handle, $inline_css);
}, 9999);

/* Final CSS (hard overrides) — loads last */
add_action('wp_enqueue_scripts', function () {
	$theme_ver = wp_get_theme(get_template())->get('Version');

	$over_rel  = 'css/overrides.css';
	$over_path = trailingslashit(get_stylesheet_directory()) . $over_rel;
	$over_uri  = trailingslashit(get_stylesheet_directory_uri()) . $over_rel;
	$over_ver  = sek_file_ver($over_path, $theme_ver);

	$deps = array_filter([
		( wp_style_is('blocksy-styles','registered') ? 'blocksy-styles' : ( wp_style_is('ct-main','registered') ? 'ct-main' : null ) ),
		( wp_style_is('elementor-frontend','registered') ? 'elementor-frontend' : null ),
		'child-style',
		( wp_style_is('sek-acc-v3','enqueued') || wp_style_is('sek-acc-v3','registered') ? 'sek-acc-v3' : null ),
	]);
	wp_enqueue_style('sek-final-overrides', $over_uri, $deps, $over_ver);
}, 10000);

/* --------------------------------------------------------------------------
   Body classes
-------------------------------------------------------------------------- */
add_filter('body_class', function ($classes) {
	$classes[] = 'theme-sek';
	if (is_page()) {
		$id = get_queried_object_id();
		if (get_post_meta($id, 'sek_bg_image', true)) $classes[] = 'has-page-bg';
		if (get_post_meta($id, 'sek_bg_video', true)) $classes[] = 'has-page-video';
	}
	return $classes;
});

/* --------------------------------------------------------------------------
   Customizer: global overlay defaults
-------------------------------------------------------------------------- */
add_action('customize_register', function (WP_Customize_Manager $wp_customize) {
	$section = 'sek_overlay_section';

	$wp_customize->add_section($section, [
		'title'       => __('Overlay', 'blocksy-child'),
		'priority'    => 35,
		'description' => __('Global overlay defaults. Pages can override with Pods fields.', 'blocksy-child'),
	]);

	$wp_customize->add_setting('sek_overlay_global_enable', [
		'default'           => true,
		'sanitize_callback' => static function($v){ return (bool) $v; },
		'transport'         => 'refresh',
	]);
	$wp_customize->add_control('sek_overlay_global_enable', [
		'section' => $section,
		'label'   => __('Enable overlay globally', 'blocksy-child'),
		'type'    => 'checkbox',
	]);

	$wp_customize->add_setting('sek_overlay_global_color', [
		'default'           => '#000000',
		'sanitize_callback' => 'sanitize_hex_color',
		'transport'         => 'refresh',
	]);
	$wp_customize->add_control(new WP_Customize_Color_Control(
		$wp_customize,
		'sek_overlay_global_color',
		[
			'section' => $section,
			'label'   => __('Overlay color', 'blocksy-child'),
		]
	));

	$wp_customize->add_setting('sek_overlay_global_opacity', [
		'default'           => 0.5,
		'sanitize_callback' => function ($v) {
			$v = floatval($v);
			if ($v > 1) $v = $v / 100;
			return max(0, min(1, $v));
		},
		'transport'         => 'refresh',
	]);
	$wp_customize->add_control('sek_overlay_global_opacity', [
		'section'     => $section,
		'label'       => __('Overlay opacity (0–1)', 'blocksy-child'),
		'type'        => 'number',
		'input_attrs' => ['min' => 0, 'max' => 1, 'step' => 0.05],
	]);
});

/* --------------------------------------------------------------------------
   Background video + overlay (skip in Elementor preview to avoid editor issues)
-------------------------------------------------------------------------- */
add_action('wp_body_open', function () {
	// Skip in Elementor preview & Customizer preview to keep editors clean
	if ( isset($_GET['elementor-preview']) || is_customize_preview() ) return;

	if (is_page()) {
		$id         = get_queried_object_id();
		$video_raw  = get_post_meta($id, 'sek_bg_video', true);
		$poster_raw = get_post_meta($id, 'sek_bg_video_poster', true);
		$muted      = get_post_meta($id, 'sek_bg_video_muted', true);
		$loop       = get_post_meta($id, 'sek_bg_video_loop', true);
		$mobdis     = get_post_meta($id, 'sek_bg_video_mobile_disable', true);

		$video_url  = sek_resolve_media_url($video_raw, 'video');
		$poster_url = sek_resolve_media_url($poster_raw, 'image');

		if ($video_url) {
			$type = sek_video_mime_from_url($video_url);
			echo '<video class="site-bg-video" aria-hidden="true" playsinline autoplay ' .
				(($muted === '' || $muted == '1' || $muted === 1) ? 'muted ' : '') .
				(($loop  === '' || $loop  == '1' || $loop  === 1) ? 'loop '  : '') .
				($poster_url ? 'poster="' . esc_attr($poster_url) . '" ' : '') .
				'data-disable-on-mobile="' . (($mobdis == '1' || $mobdis === 1 || $mobdis === '') ? 'true' : 'false') . '">';
			echo '<source src="' . esc_url($video_url) . '"' . ($type ? ' type="' . esc_attr($type) . '"' : '') . ' />';
			echo '</video>';
		}
	}

	echo '<div class="site-overlay" aria-hidden="true"></div>';
}, 5);

/* --------------------------------------------------------------------------
   Force correct ?ver= (mtime) on our assets only
-------------------------------------------------------------------------- */
add_filter('style_loader_src', function ($src, $handle) {
	$map = [
		'parent-style'        => get_template_directory()   . '/style.css',
		'child-style'         => get_stylesheet_directory() . '/style.css',
		'sek-acc-v3'          => get_stylesheet_directory() . '/css/accordion-elementor.v3.css',
		'sek-final-overrides' => get_stylesheet_directory() . '/css/overrides.css',
	];
	if (!isset($map[$handle])) return $src;
	$ver = file_exists($map[$handle]) ? (string) filemtime($map[$handle]) : wp_get_theme(get_template())->get('Version');
	$src = remove_query_arg('ver', $src);
	return add_query_arg('ver', $ver, $src);
}, 9999, 2);

add_filter('script_loader_src', function ($src, $handle) {
	if ($handle !== 'blocksy-child-menu') return $src;
	$path = get_stylesheet_directory() . '/js/menu.js';
	$ver  = file_exists($path) ? (string) filemtime($path) : wp_get_theme(get_template())->get('Version');
	$src  = remove_query_arg('ver', $src);
	return add_query_arg('ver', $ver, $src);
}, 9999, 2);

/* --------------------------------------------------------------------------
   Contact Form 7 — server-side timestamp (single set of hooks)
-------------------------------------------------------------------------- */
add_action('wpcf7_before_send_mail', function( $cf7, &$abort = null, $submission = null ) {
	$now = date_i18n( 'Y-m-d H:i:s', current_time( 'timestamp' ) );
	$_POST['submitdate'] = $now;
	if ( $submission instanceof WPCF7_Submission ) {
		if ( method_exists( $submission, 'get_posted_data' ) ) {
			$data = $submission->get_posted_data();
			$data['submitdate'] = $now;
			if ( method_exists( $submission, 'set_posted_data' ) ) {
				$submission->set_posted_data( $data );
			}
		}
	}
}, 10, 3);

add_filter('wpcf7_form_hidden_fields', function ( $hidden ) {
	$hidden['submitdate'] = date_i18n('Y-m-d H:i:s', current_time('timestamp'));
	return $hidden;
});

add_filter('wpcf7_posted_data', function( $data ) {
	$now = date_i18n('Y-m-d H:i:s', current_time('timestamp'));
	$data['submitdate'] = $now;
	$_POST['submitdate'] = $now;
	return $data;
});
