<?php
/**
 * Custom WooCommerce Order Statuses — register and manage custom statuses.
 *
 * Allows admins to create custom order statuses with custom colors and icons.
 * Enhances the orders list with status columns, filters, and phone number display.
 *
 * @package Mersal_Notif
 */

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

class Mersal_Notif_Order_Statuses {

	const OPTION = 'mnotif_custom_order_statuses';

	/**
	 * Initialize hooks.
	 */
	public function init() {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return;
		}

		// Register custom statuses.
		add_action( 'init', array( $this, 'register_statuses' ) );

		// Add status column to orders list.
		add_filter( 'manage_edit-shop_order_columns', array( $this, 'add_columns' ) );
		add_action( 'manage_shop_order_posts_custom_column', array( $this, 'render_columns' ), 10, 2 );

		// Add status filter dropdown.
		add_filter( 'woocommerce_orders_table_column_filters', array( $this, 'add_filters' ) );
	}

	/**
	 * Get all custom statuses.
	 *
	 * @return array
	 */
	public static function get_statuses() {
		$statuses = get_option( self::OPTION, array() );
		return is_array( $statuses ) ? $statuses : array();
	}

	/**
	 * Add a custom status.
	 *
	 * @param string $slug  Status slug (without wc- prefix).
	 * @param string $label Human label.
	 * @param string $color Hex color.
	 * @param string $icon  Material icon name.
	 * @return bool
	 */
	public static function add_status( $slug, $label, $color = '#25D366', $icon = 'check_circle' ) {
		$statuses = self::get_statuses();
		$slug     = sanitize_key( $slug );
		if ( empty( $slug ) || empty( $label ) ) {
			return false;
		}
		$statuses[ $slug ] = array(
			'slug'  => $slug,
			'label' => sanitize_text_field( $label ),
			'color' => sanitize_hex_color( $color ),
			'icon'  => sanitize_text_field( $icon ),
		);
		return update_option( self::OPTION, $statuses, false );
	}

	/**
	 * Remove a custom status.
	 *
	 * @param string $slug Status slug.
	 * @return bool
	 */
	public static function remove_status( $slug ) {
		$statuses = self::get_statuses();
		unset( $statuses[ sanitize_key( $slug ) ] );
		return update_option( self::OPTION, $statuses, false );
	}

	/**
	 * Register custom order statuses with WooCommerce.
	 */
	public function register_statuses() {
		$statuses = self::get_statuses();
		foreach ( $statuses as $slug => $data ) {
			register_post_status( 'wc-' . $slug, array(
				'label'                     => $data['label'],
				'public'                    => true,
				'exclude_from_search'       => false,
				'show_in_admin_all_list'    => true,
				'show_in_admin_status_list' => true,
				/* translators: %s: order count */
				'label_count'               => _n_noop( $data['label'] . ' <span class="count">(%s)</span>', $data['label'] . ' <span class="count">(%s)</span>', 'mersal-notifications' ),
			) );
		}
	}

	/**
	 * Add custom status columns to orders list.
	 *
	 * @param array $columns Existing columns.
	 * @return array
	 */
	public function add_columns( $columns ) {
		$statuses = self::get_statuses();
		if ( empty( $statuses ) ) {
			return $columns;
		}

		// Add phone number column.
		$new_columns = array();
		foreach ( $columns as $key => $label ) {
			$new_columns[ $key ] = $label;
			if ( 'order_status' === $key ) {
				$new_columns['mnotif_phone'] = __( 'Phone', 'mersal-notifications' );
			}
		}
		return $new_columns;
	}

	/**
	 * Render custom column content.
	 *
	 * @param string $column  Column name.
	 * @param int    $post_id Post ID.
	 */
	public function render_columns( $column, $post_id ) {
		if ( 'mnotif_phone' !== $column ) {
			return;
		}

		$order = wc_get_order( $post_id );
		if ( ! $order ) {
			return;
		}

		$phone = $order->get_billing_phone();
		if ( empty( $phone ) ) {
			echo '<span style="color:#ccc;">—</span>';
			return;
		}

		// Show country flag + phone.
		$country = $order->get_billing_country();
		$flag    = '';
		if ( $country ) {
			$code = strtolower( $country );
			if ( strlen( $code ) === 2 ) {
				$upper = strtoupper( $code );
				$flag  = mb_convert_encoding( implode( '', array_map( function ( $c ) {
					return '&#x' . ( 0x1F1A5 + ord( $c ) ) . ';';
				}, str_split( $upper ) ) ), 'UTF-8', 'HTML-ENTITIES' );
			}
		}

		// Check verification status.
		$verified = get_user_meta( $order->get_customer_id(), 'motp_phone_verified', true );
		$badge    = ! empty( $verified )
			? '<span style="color:#25D366;font-size:10px;">&#x2714;</span>'
			: '<span style="color:#e74c3c;font-size:10px;">&#x2716;</span>';

		printf(
			'<span style="font-size:12px;">%s %s %s</span>',
			$flag,
			esc_html( $phone ),
			$badge
		);
	}

	/**
	 * Add status filter options.
	 *
	 * @param array $filters Existing filters.
	 * @return array
	 */
	public function add_filters( $filters ) {
		$statuses = self::get_statuses();
		foreach ( $statuses as $slug => $data ) {
			$filters[ 'wc-' . $slug ] = $data['label'];
		}
		return $filters;
	}
}
