<?php
declare(strict_types=1);
if ( ! defined( 'ABSPATH' ) ) { exit; }
/**
 * Page Auto-Generation & Theme Activation.
 * @package WTE_Business_Card
 */

function wte_theme_activation_setup(): void {
	wte_create_front_page();
	flush_rewrite_rules();
	set_transient( 'wte_activation_notice', true, 30 );
}
add_action( 'after_switch_theme', 'wte_theme_activation_setup' );

function wte_create_front_page(): void {
	$existing = get_pages( [ 'meta_key' => '_wte_is_front_page', 'meta_value' => '1', 'number' => 1 ] );
	if ( ! empty( $existing ) ) return;
	$page_id = wp_insert_post( [
		'post_title' => 'ホーム', 'post_name' => 'home', 'post_status' => 'publish',
		'post_type' => 'page', 'post_content' => '',
	] );
	if ( ! is_wp_error( $page_id ) ) {
		update_post_meta( $page_id, '_wte_is_front_page', '1' );
		update_option( 'show_on_front', 'page' );
		update_option( 'page_on_front', $page_id );
		update_option( 'page_for_posts', 0 );
	}
}

function wte_maybe_create_contact_page(): void {
	$email = get_theme_mod( 'wte_contact_email', '' );
	if ( empty( $email ) ) return;
	$existing = get_pages( [ 'meta_key' => '_wte_is_contact_page', 'meta_value' => '1', 'number' => 1 ] );
	if ( ! empty( $existing ) ) return;
	$page_id = wp_insert_post( [
		'post_title' => get_theme_mod( 'wte_contact_page_title', 'お問い合わせ' ),
		'post_name' => 'contact', 'post_status' => 'publish', 'post_type' => 'page', 'post_content' => '',
	] );
	if ( ! is_wp_error( $page_id ) ) {
		update_post_meta( $page_id, '_wte_is_contact_page', '1' );
	}
}
add_action( 'customize_save_after', 'wte_maybe_create_contact_page' );

function wte_show_activation_notice(): void {
	if ( ! get_transient( 'wte_activation_notice' ) ) return;
	if ( ! current_user_can( 'manage_options' ) ) return;
	delete_transient( 'wte_activation_notice' );
	printf(
		'<div class="notice notice-success is-dismissible"><p><strong>WTE Business Card</strong> %s <a href="%s">%s</a></p></div>',
		esc_html__( 'が有効化されました！カスタマイザーから各種情報を設定してください。', 'wte_' ),
		esc_url( admin_url( 'customize.php' ) ),
		esc_html__( 'カスタマイザーを開く →', 'wte_' )
	);
}
add_action( 'admin_notices', 'wte_show_activation_notice' );
