<?php
if ( ! defined('ABSPATH') ) exit;

class HBDEV_Budget_Metabox {
	public static function init() {
		add_action('add_meta_boxes', [__CLASS__, 'add_boxes']);
		add_action('save_post_booking', [__CLASS__, 'save'], 10, 2);
	}

	public static function add_boxes() {
		add_meta_box(
			'hbdev_booking_details',
			__('Buchungsdetails', 'hbdev-budget'),
			[__CLASS__, 'render_box'],
			'booking',
			'normal',
			'high'
		);
	}

	public static function render_box( WP_Post $post ) {
		$amount = get_post_meta($post->ID, 'booking_amount', true);
		$date   = get_post_meta($post->ID, 'booking_date', true);
		if (!is_string($date) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)$date)) {
			$tz = wp_timezone();
			$date = (new DateTimeImmutable('now', $tz))->format('Y-m-d');
		}

		wp_nonce_field('hbdev_booking_details', 'hbdev_booking_nonce');
		?>
		<style>
			.hbdev-fields { display: grid; grid-template-columns: 160px 1fr; gap: 8px 12px; align-items: center; }
			.hbdev-fields input[type="number"] { max-width: 160px; }
			.hbdev-fields input[type="date"] { max-width: 190px; }
			.hbdev-help { color:#666; font-size:12px; grid-column: 2 / 3; }
		</style>
		<div class="hbdev-fields">
			<label for="hbdev_booking_date"><?php esc_html_e('Datum', 'hbdev-budget'); ?></label>
			<input type="date" id="hbdev_booking_date" name="hbdev_booking_date" value="<?php echo esc_attr($date); ?>" />

			<label for="hbdev_booking_amount"><?php esc_html_e('Betrag (EUR)', 'hbdev-budget'); ?></label>
			<input type="number" id="hbdev_booking_amount" name="hbdev_booking_amount" value="<?php echo esc_attr($amount); ?>" step="0.01" inputmode="decimal" />
			<div class="hbdev-help"><?php esc_html_e('Tipp: Komma oder Punkt für Dezimalstellen erlaubt. Für Einnahmen/Ausgaben entscheiden spätere Auswertungen anhand der Kategorie.', 'hbdev-budget'); ?></div>
		</div>
		<?php
	}

	public static function save( $post_id, WP_Post $post ) {
		// Nonce prüfen
		if ( ! isset($_POST['hbdev_booking_nonce']) || ! wp_verify_nonce($_POST['hbdev_booking_nonce'], 'hbdev_booking_details') ) {
			return;
		}
		// Autosave / Revision ignorieren
		if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
		if ( wp_is_post_revision($post_id) ) return;

		// Berechtigung
		if ( ! current_user_can('edit_post', $post_id) ) return;

		// Erwartete Felder
		$date_in   = isset($_POST['hbdev_booking_date']) ? sanitize_text_field($_POST['hbdev_booking_date']) : '';
		$amount_in = isset($_POST['hbdev_booking_amount']) ? (string) $_POST['hbdev_booking_amount'] : '';

		// Datum validieren -> Y-m-d, Standard: heutiges Datum
		$valid_date = null;
		if ( preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_in) ) {
			$valid_date = $date_in;
		} else {
			$valid_date = (new DateTimeImmutable('now', wp_timezone()))->format('Y-m-d');
		}

		// Betrag normalisieren: Komma in Punkt umwandeln, nur Ziffern/Punkt/Minus erlauben
		$normalized = str_replace(["\xC2\xA0", ' '], '', $amount_in); // geschütztes Leerzeichen & Space entfernen
		$normalized = str_replace([','], '.', $normalized);
		$normalized = preg_replace('/[^0-9\.-]/', '', $normalized);
		$amount = is_numeric($normalized) ? (float) $normalized : 0.0;

		update_post_meta($post_id, 'booking_date', $valid_date);
		update_post_meta($post_id, 'booking_amount', $amount);
	}
}

HBDEV_Budget_Metabox::init();
