<?php
/**
 * Odysseo Core — per-page content meta box.
 *
 * Adds the "Page Content" meta box to Home/About/etc. pages so their copy,
 * timeline, recognitions, FAQs and per-section show/hide toggles are edited on
 * the page itself (written as _odm_* post meta). The THEME reads these values
 * via odysseo_pf()/odysseo_section_visible() and falls back to Customizer/default
 * when this plugin is inactive.
 *
 * @package    OdysseoCore
 * @author     Chandrabhan Shekhawat
 * @company    Gigai Kripa Services
 * @link       https://gigaikripaservices.com/
 * @copyright  Copyright (c) 2026, Gigai Kripa Services
 */

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

/**
 * Per-page section toggles (rendered in the page meta box, saved as _odm_show_KEY).
 */
function odysseo_pagemeta_sections() {
	return array(
		'page-templates/template-home.php' => array(
			'home_hero'         => __( 'Hero', 'odysseo-core' ),
			'home_marquee'      => __( 'Marquee ticker', 'odysseo-core' ),
			'home_why'          => __( 'Why Us', 'odysseo-core' ),
			'home_destinations' => __( 'Destinations', 'odysseo-core' ),
			'home_packages'     => __( 'Tour Packages', 'odysseo-core' ),
			'home_stats'        => __( 'Stats band', 'odysseo-core' ),
			'home_fleet'        => __( 'Fleet', 'odysseo-core' ),
			'home_cta'          => __( 'Talk-to-owner CTA', 'odysseo-core' ),
			'home_story'        => __( 'Story / Process', 'odysseo-core' ),
			'home_testimonials' => __( 'Testimonials', 'odysseo-core' ),
			'home_blog'         => __( 'Latest Blog', 'odysseo-core' ),
		),
		'page-templates/template-about.php' => array(
			'about_story'        => __( 'Story', 'odysseo-core' ),
			'about_founder'      => __( 'Founder', 'odysseo-core' ),
			'about_marquee'      => __( 'Marquee', 'odysseo-core' ),
			'about_timeline'     => __( 'Journey / Timeline', 'odysseo-core' ),
			'about_pillars'      => __( 'Pillars', 'odysseo-core' ),
			'about_stats'        => __( 'Stats band', 'odysseo-core' ),
			'about_why'          => __( 'Why Travel With Us', 'odysseo-core' ),
			'about_recognitions' => __( 'Recognitions', 'odysseo-core' ),
			'about_faq'          => __( 'FAQ', 'odysseo-core' ),
		),
	);
}

/**
 * Field schema per page template.
 * Field = array( label, type ) where type = text | area | html_area | rows.
 */
function odysseo_pagemeta_schema() {
	return array(
		'page-templates/template-home.php' => array(
			'title'  => __( 'Home Page Content', 'odysseo-core' ),
			'fields' => array(
				'home_hero_title'     => array( __( 'Hero Title (HTML allowed)', 'odysseo-core' ), 'html_area' ),
				'home_hero_subtitle'  => array( __( 'Hero Subtitle', 'odysseo-core' ), 'area' ),
				'why_feat_description'=> array( __( '“Why Us” Card Description', 'odysseo-core' ), 'area' ),
				'home_pkg_sub'        => array( __( 'Packages Section Subtitle', 'odysseo-core' ), 'area' ),
			),
		),
		'page-templates/template-about.php' => array(
			'title'  => __( 'About Page Content', 'odysseo-core' ),
			'fields' => array(
				'banner_about_sub'    => array( __( 'Banner Subtitle', 'odysseo-core' ), 'area' ),
				'about_story_p1'      => array( __( 'Story — Paragraph 1 (HTML allowed)', 'odysseo-core' ), 'html_area' ),
				'about_story_p2'      => array( __( 'Story — Paragraph 2 (HTML allowed)', 'odysseo-core' ), 'html_area' ),
				'about_story_bullets' => array( __( 'Story — Bullets (one per line)', 'odysseo-core' ), 'area' ),
				'founder_quote'       => array( __( 'Founder — Quote', 'odysseo-core' ), 'area' ),
				'founder_bio'         => array( __( 'Founder — Bio (HTML allowed)', 'odysseo-core' ), 'html_area' ),
				'journey_title'       => array( __( 'Journey — Heading (HTML allowed)', 'odysseo-core' ), 'html_area' ),
				'pillar_mission_body' => array( __( 'Mission — Body (HTML allowed)', 'odysseo-core' ), 'html_area' ),
				'pillar_vision_title' => array( __( 'Vision — Title', 'odysseo-core' ), 'text' ),
				'pillar_vision_body'  => array( __( 'Vision — Body (HTML allowed)', 'odysseo-core' ), 'html_area' ),
				'timeline'            => array( __( 'Timeline rows — one per line: Title :: Body :: Tag', 'odysseo-core' ), 'rows' ),
				'recognitions'        => array( __( 'Recognitions — one per line: Title :: Subtitle :: FontAwesome icon', 'odysseo-core' ), 'rows' ),
				'faqs'                => array( __( 'FAQs — one per line: Question :: Answer (HTML allowed)', 'odysseo-core' ), 'rows' ),
			),
		),
		'page-templates/template-contact.php' => array(
			'title'  => __( 'Contact Page Content', 'odysseo-core' ),
			'fields' => array( 'banner_contact_sub' => array( __( 'Banner Subtitle', 'odysseo-core' ), 'area' ) ),
		),
		'page-templates/template-blogs.php' => array(
			'title'  => __( 'Blog Page Content', 'odysseo-core' ),
			'fields' => array( 'banner_blogs_sub' => array( __( 'Banner Subtitle', 'odysseo-core' ), 'area' ) ),
		),
		'page-templates/template-fleets.php' => array(
			'title'  => __( 'Fleet Page Content', 'odysseo-core' ),
			'fields' => array( 'banner_fleets_sub' => array( __( 'Banner Subtitle', 'odysseo-core' ), 'area' ) ),
		),
		'page-templates/template-gallery.php' => array(
			'title'  => __( 'Gallery Page Content', 'odysseo-core' ),
			'fields' => array( 'banner_gallery_sub' => array( __( 'Banner Subtitle', 'odysseo-core' ), 'area' ) ),
		),
	);
}

/**
 * Register the content meta box on pages that use a covered template.
 */
function odysseo_pagemeta_add_box() {
	$template = get_page_template_slug( get_the_ID() );
	$schema   = odysseo_pagemeta_schema();
	if ( $template && isset( $schema[ $template ] ) ) {
		add_meta_box(
			'odysseo_page_content',
			$schema[ $template ]['title'],
			'odysseo_pagemeta_render_box',
			'page',
			'normal',
			'high',
			array( 'template' => $template )
		);
	}
}
add_action( 'add_meta_boxes_page', 'odysseo_pagemeta_add_box' );

/**
 * Render the meta box.
 */
function odysseo_pagemeta_render_box( $post, $box ) {
	$template = $box['args']['template'];
	$schema   = odysseo_pagemeta_schema();
	$fields   = $schema[ $template ]['fields'];
	wp_nonce_field( 'odysseo_pagemeta_save', 'odysseo_pagemeta_nonce' );
	echo '<p style="color:#666;margin:0 0 14px;">' . esc_html__( 'Leave a field blank to use the theme default. These fields edit only this page.', 'odysseo-core' ) . '</p>';

	foreach ( $fields as $key => $def ) {
		list( $label, $type ) = $def;
		$id  = 'odm_' . $key;
		echo '<p style="margin:0 0 16px;">';
		echo '<label for="' . esc_attr( $id ) . '"><strong>' . esc_html( $label ) . '</strong></label><br>';

		if ( 'rows' === $type ) {
			$raw = get_post_meta( $post->ID, '_odm_' . $key, true );
			if ( '' === $raw ) {
				$lines = array();
				foreach ( odysseo_default_rows( $key ) as $row ) {
					$lines[] = implode( ' :: ', $row );
				}
				$raw = implode( "\n", $lines );
			}
			echo '<textarea id="' . esc_attr( $id ) . '" name="' . esc_attr( $id ) . '" rows="8" style="width:100%;font-family:monospace;font-size:12px;">' . esc_textarea( $raw ) . '</textarea>';
		} else {
			$val = get_post_meta( $post->ID, '_odm_' . $key, true );
			if ( '' === $val ) {
				$val = get_theme_mod( $key, '' );
			}
			if ( 'text' === $type ) {
				echo '<input type="text" id="' . esc_attr( $id ) . '" name="' . esc_attr( $id ) . '" value="' . esc_attr( $val ) . '" style="width:100%;">';
			} else {
				$rows = ( 'html_area' === $type ) ? 4 : 3;
				echo '<textarea id="' . esc_attr( $id ) . '" name="' . esc_attr( $id ) . '" rows="' . (int) $rows . '" style="width:100%;">' . esc_textarea( $val ) . '</textarea>';
			}
		}
		echo '</p>';
	}

	// Section show/hide toggles for this template.
	$sections = odysseo_pagemeta_sections();
	if ( isset( $sections[ $template ] ) ) {
		echo '<hr><p style="margin:0 0 6px;"><strong>' . esc_html__( 'Sections (show / hide)', 'odysseo-core' ) . '</strong></p>';
		foreach ( $sections[ $template ] as $skey => $slabel ) {
			$vis = odysseo_section_visible( $skey, $post->ID );
			echo '<label style="display:block;margin:3px 0;"><input type="checkbox" name="odm_show_' . esc_attr( $skey ) . '" value="1" ' . checked( $vis, true, false ) . '> ' . esc_html( $slabel ) . '</label>';
		}
	}
}

/**
 * Save the meta box.
 */
function odysseo_pagemeta_save( $post_id ) {
	if ( ! isset( $_POST['odysseo_pagemeta_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['odysseo_pagemeta_nonce'] ) ), 'odysseo_pagemeta_save' ) ) return;
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
	if ( ! current_user_can( 'edit_page', $post_id ) ) return;

	$template = get_page_template_slug( $post_id );
	$schema   = odysseo_pagemeta_schema();
	if ( ! $template || ! isset( $schema[ $template ] ) ) return;

	foreach ( $schema[ $template ]['fields'] as $key => $def ) {
		$type  = $def[1];
		$field = 'odm_' . $key;
		if ( ! isset( $_POST[ $field ] ) ) continue;
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized on the next lines by field type; nonce verified above.
		$raw = wp_unslash( $_POST[ $field ] );
		if ( 'text' === $type ) {
			$clean = sanitize_text_field( $raw );
		} else {
			// area / html_area / rows all may contain limited HTML.
			$clean = wp_kses_post( $raw );
		}
		if ( '' === trim( $clean ) ) {
			delete_post_meta( $post_id, '_odm_' . $key );
		} else {
			update_post_meta( $post_id, '_odm_' . $key, $clean );
		}
	}

	// Section show/hide toggles (unchecked boxes are not posted -> stored as '0').
	$sections = odysseo_pagemeta_sections();
	if ( isset( $sections[ $template ] ) ) {
		foreach ( $sections[ $template ] as $skey => $slabel ) {
			update_post_meta( $post_id, '_odm_show_' . $skey, isset( $_POST[ 'odm_show_' . $skey ] ) ? '1' : '0' );
		}
	}
}
add_action( 'save_post_page', 'odysseo_pagemeta_save' );

/**
 * Backfills page meta from existing Customizer values once per install (guarded
 * by an option flag) so content set in the Customizer is editable on the page.
 */
function odysseo_pagemeta_migrate() {
	if ( get_option( 'odysseo_pagemeta_migrated' ) ) return;

	$schema = odysseo_pagemeta_schema();
	foreach ( $schema as $template => $cfg ) {
		$pages = get_posts( array(
			'post_type'   => 'page',
			'post_status' => 'any',
			'numberposts' => -1,
			'meta_key'    => '_wp_page_template', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- One-time migration when the theme is switched.
			'meta_value'  => $template, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- One-time migration when the theme is switched.
			'fields'      => 'ids',
		) );
		foreach ( $pages as $pid ) {
			foreach ( $cfg['fields'] as $key => $def ) {
				if ( '' !== get_post_meta( $pid, '_odm_' . $key, true ) ) continue;
				if ( 'rows' === $def[1] ) {
					$lines = odysseo_pagemeta_collect_legacy_rows( $key );
					if ( $lines ) update_post_meta( $pid, '_odm_' . $key, $lines );
				} else {
					$mod = get_theme_mod( $key, null );
					if ( null !== $mod && '' !== $mod ) {
						update_post_meta( $pid, '_odm_' . $key, $mod );
					}
				}
			}
		}
	}
	update_option( 'odysseo_pagemeta_migrated', 1 );
}
add_action( 'after_switch_theme', 'odysseo_pagemeta_migrate', 30 );

/**
 * Assembles per-index theme_mods (tl{i}_*, recog{i}_*, faq{i}_*) into a rows
 * string, returning it only when at least one value was customised.
 *
 * @param string $key Rows field key (timeline|recognitions|faqs).
 * @return string
 */
function odysseo_pagemeta_collect_legacy_rows( $key ) {
	$map = array(
		'timeline'     => array( 'prefix' => 'tl',    'max' => 5, 'cols' => array( '_title', '_body', '_tag' ) ),
		'recognitions' => array( 'prefix' => 'recog', 'max' => 6, 'cols' => array( '_title', '_sub', '_icon' ) ),
		'faqs'         => array( 'prefix' => 'faq',   'max' => 7, 'cols' => array( '_q', '_a' ) ),
	);
	if ( ! isset( $map[ $key ] ) ) return '';
	$cfg = $map[ $key ];
	$lines = array();
	$found = false;
	for ( $i = 1; $i <= $cfg['max']; $i++ ) {
		$cells = array();
		foreach ( $cfg['cols'] as $col ) {
			$mod = get_theme_mod( $cfg['prefix'] . $i . $col, null );
			if ( null !== $mod && '' !== $mod ) $found = true;
			$cells[] = (string) $mod;
		}
		if ( '' !== trim( implode( '', $cells ) ) ) {
			$lines[] = implode( ' :: ', $cells );
		}
	}
	return $found ? implode( "\n", $lines ) : '';
}
