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

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

	public static function add_boxes() {
		add_meta_box(
			'hbdev_subscription_details',
			__('Abo-Details', 'hbdev-budget'),
			[__CLASS__, 'render_box'],
			'subscription',
			'normal',
			'high'
		);
	}

	public static function render_box( WP_Post $post ) {
		$amount = get_post_meta($post->ID, 'subscription_amount', true);
		$start  = get_post_meta($post->ID, 'subscription_start', true);
		$status = get_post_meta($post->ID, 'subscription_status', true);
		$end    = get_post_meta($post->ID, 'subscription_end', true);
		$repeat = get_post_meta($post->ID, 'subscription_repeat', true);
		$note   = get_post_meta($post->ID, 'subscription_note', true);

		$tz = wp_timezone();
		$today = (new DateTimeImmutable('now', $tz))->format('Y-m-d');
		if (!is_string($start) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)$start)) {
			$start = $today;
		}

		$repeat = in_array($repeat, ['weekly','monthly','yearly'], true) ? $repeat : 'monthly';
		$status = in_array($status, ['running','cancelled'], true) ? $status : 'running';

		wp_nonce_field('hbdev_subscription_details', 'hbdev_subscription_nonce');
		?>
		<style>
			.hbdev-fields { display: grid; grid-template-columns: 180px 1fr; gap: 8px 12px; align-items: center; }
			.hbdev-fields input[type="number"] { max-width: 160px; }
			.hbdev-fields input[type="date"], .hbdev-fields select { max-width: 220px; }
			.hbdev-help { color:#666; font-size:12px; grid-column: 2 / 3; }
			.hbdev-note { width: 100%; max-width: 560px; }
		</style>
		<div class="hbdev-fields">
			<label for="hbdev_subscription_amount"><?php esc_html_e('Betrag (EUR)', 'hbdev-budget'); ?></label>
			<input type="number" id="hbdev_subscription_amount" name="hbdev_subscription_amount" value="<?php echo esc_attr($amount); ?>" step="0.01" inputmode="decimal" />
			<div class="hbdev-help"><?php esc_html_e('Negative Werte für Ausgaben, positive für Einnahmen.', 'hbdev-budget'); ?></div>

			<label for="hbdev_subscription_start"><?php esc_html_e('Starttermin', 'hbdev-budget'); ?></label>
			<input type="date" id="hbdev_subscription_start" name="hbdev_subscription_start" value="<?php echo esc_attr($start); ?>" />

			<label for="hbdev_subscription_status"><?php esc_html_e('Status', 'hbdev-budget'); ?></label>
			<select id="hbdev_subscription_status" name="hbdev_subscription_status">
				<option value="running" <?php selected($status, 'running'); ?>><?php esc_html_e('laufend', 'hbdev-budget'); ?></option>
				<option value="cancelled" <?php selected($status, 'cancelled'); ?>><?php esc_html_e('gekündigt', 'hbdev-budget'); ?></option>
			</select>

			<label for="hbdev_subscription_end"><?php esc_html_e('Endtermin (optional)', 'hbdev-budget'); ?></label>
			<input type="date" id="hbdev_subscription_end" name="hbdev_subscription_end" value="<?php echo esc_attr($end); ?>" />

			<label for="hbdev_subscription_repeat"><?php esc_html_e('Wiederholung', 'hbdev-budget'); ?></label>
			<select id="hbdev_subscription_repeat" name="hbdev_subscription_repeat">
				<option value="weekly" <?php selected($repeat, 'weekly'); ?>><?php esc_html_e('wöchentlich', 'hbdev-budget'); ?></option>
				<option value="monthly" <?php selected($repeat, 'monthly'); ?>><?php esc_html_e('monatlich', 'hbdev-budget'); ?></option>
				<option value="yearly" <?php selected($repeat, 'yearly'); ?>><?php esc_html_e('jährlich', 'hbdev-budget'); ?></option>
			</select>

			<label for="hbdev_subscription_note"><?php esc_html_e('Bemerkung', 'hbdev-budget'); ?></label>
			<textarea id="hbdev_subscription_note" name="hbdev_subscription_note" class="hbdev-note" rows="3"><?php echo esc_textarea((string)$note); ?></textarea>
		</div>
		<?php
	}

	public static function save( $post_id, WP_Post $post ) {
		if ( ! isset($_POST['hbdev_subscription_nonce']) || ! wp_verify_nonce($_POST['hbdev_subscription_nonce'], 'hbdev_subscription_details') ) {
			return;
		}
		if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
		if ( wp_is_post_revision($post_id) ) return;
		if ( ! current_user_can('edit_post', $post_id) ) return;

		$amount_in = isset($_POST['hbdev_subscription_amount']) ? (string) $_POST['hbdev_subscription_amount'] : '';
		$start_in  = isset($_POST['hbdev_subscription_start']) ? sanitize_text_field($_POST['hbdev_subscription_start']) : '';
		$status_in = isset($_POST['hbdev_subscription_status']) ? sanitize_text_field($_POST['hbdev_subscription_status']) : 'running';
		$end_in    = isset($_POST['hbdev_subscription_end']) ? sanitize_text_field($_POST['hbdev_subscription_end']) : '';
		$repeat_in = isset($_POST['hbdev_subscription_repeat']) ? sanitize_text_field($_POST['hbdev_subscription_repeat']) : 'monthly';
		$note_in   = isset($_POST['hbdev_subscription_note']) ? (string) $_POST['hbdev_subscription_note'] : '';

		$normalized = str_replace(["\xC2\xA0", ' '], '', $amount_in);
		$normalized = str_replace([','], '.', $normalized);
		$normalized = preg_replace('/[^0-9\.-]/', '', $normalized);
		$amount = is_numeric($normalized) ? (float) $normalized : 0.0;

		$start = preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_in) ? $start_in : (new DateTimeImmutable('now', wp_timezone()))->format('Y-m-d');
		$end   = preg_match('/^\d{4}-\d{2}-\d{2}$/', $end_in) ? $end_in : '';
		$status = in_array($status_in, ['running','cancelled'], true) ? $status_in : 'running';
		$repeat = in_array($repeat_in, ['weekly','monthly','yearly'], true) ? $repeat_in : 'monthly';

		update_post_meta($post_id, 'subscription_amount', $amount);
		update_post_meta($post_id, 'subscription_start', $start);
		update_post_meta($post_id, 'subscription_status', $status);
		update_post_meta($post_id, 'subscription_end', $end);
		update_post_meta($post_id, 'subscription_repeat', $repeat);
		update_post_meta($post_id, 'subscription_note', wp_kses_post($note_in));
	}
}

HBDEV_Budget_Subscription_Metabox::init();
