<?php
/**
 * Email thông báo đơn đặt vé mới (wp_mail / WP Mail SMTP).
 *
 * @package DatvetaucaotocBooking
 */

declare(strict_types=1);

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

require_once DATVETAU_BOOKING_DIR . 'includes/admin/class-admin-format.php';

final class Datvetau_Booking_Notifier {

	public static function on_booking_created( int $booking_id ): void {
		$settings = Datvetau_Booking_Settings::all();
		if ( empty( $settings['booking_notify_enabled'] ) ) {
			return;
		}

		$recipients = self::resolve_recipients( (string) ( $settings['booking_notify_to'] ?? '' ) );
		if ( ! $recipients ) {
			return;
		}

		$booking = Datvetau_Booking_Booking_Repository::find_by_id( $booking_id );
		if ( ! $booking ) {
			return;
		}

		$passengers = Datvetau_Booking_Booking_Repository::passengers_for_booking( $booking_id );
		$route      = Datvetau_Booking_Route_Repository::find_by_id( (int) $booking['route_id'] );
		$outbound   = Datvetau_Booking_Trip_Repository::find_by_id( (int) $booking['outbound_trip_id'] );
		$inbound    = ! empty( $booking['inbound_trip_id'] )
			? Datvetau_Booking_Trip_Repository::find_by_id( (int) $booking['inbound_trip_id'] )
			: null;

		$subject = (string) ( $settings['booking_notify_subject'] ?? 'KHÁCH ĐẶT VÉ MỚI' );
		$body    = self::build_body_html( $booking, $passengers, $route, $outbound, $inbound );
		$headers = array( 'Content-Type: text/html; charset=UTF-8' );

		foreach ( $recipients as $to ) {
			wp_mail( $to, $subject, $body, $headers );
		}
	}

	/**
	 * @return list<string>
	 */
	private static function resolve_recipients( string $raw ): array {
		$raw = trim( $raw );
		if ( '' === $raw ) {
			$admin = sanitize_email( (string) get_option( 'admin_email', '' ) );
			return $admin ? array( $admin ) : array();
		}

		$parts = preg_split( '/[\s,;]+/', $raw ) ?: array();
		$out   = array();
		foreach ( $parts as $part ) {
			$email = sanitize_email( $part );
			if ( $email && is_email( $email ) ) {
				$out[] = $email;
			}
		}
		return array_values( array_unique( $out ) );
	}

	/**
	 * @param array<string,mixed>|null $route
	 * @param array<string,mixed>|null $outbound
	 * @param array<string,mixed>|null $inbound
	 * @param array<int,array<string,mixed>> $passengers
	 */
	private static function build_body_html(
		array $booking,
		array $passengers,
		?array $route,
		?array $outbound,
		?array $inbound
	): string {
		$counts = self::fare_counts( $passengers );
		$total  = (int) $booking['ticket_count'];

		$booker_name  = esc_html( (string) $booking['booker_name'] );
		$booker_phone = esc_html( (string) $booking['booker_phone'] );
		$booker_email = esc_html( (string) ( $booking['booker_email'] ?? '' ) ?: '—' );
		$code         = esc_html( (string) $booking['booking_code'] );
		$route_label  = esc_html( $route ? (string) $route['label'] : '—' );
		$total_fmt    = esc_html( number_format_i18n( (int) $booking['total_vnd'] ) . ' VND' );

		$trip_type = esc_html(
			Datvetau_Booking_Admin_Format::trip_type_label( (string) $booking['trip_type'] )
			. ' · '
			. strtoupper( (string) $booking['seat_class'] )
		);

		$qty_lines = '';
		if ( $counts['adult'] > 0 ) {
			$qty_lines .= '<div>+ ' . (int) $counts['adult'] . ' ' . esc_html__( 'người lớn', 'datvetaucaotoc-booking' ) . '</div>';
		}
		if ( $counts['child'] > 0 ) {
			$qty_lines .= '<div>+ ' . (int) $counts['child'] . ' ' . esc_html__( 'trẻ em', 'datvetaucaotoc-booking' ) . '</div>';
		}
		if ( $counts['senior'] > 0 ) {
			$qty_lines .= '<div>+ ' . (int) $counts['senior'] . ' ' . esc_html__( 'người cao tuổi', 'datvetaucaotoc-booking' ) . '</div>';
		}

		$table_rows = '';
		foreach ( $passengers as $i => $p ) {
			$line_total = (int) $p['unit_price_vnd'] * (int) $p['legs_count'];
			$table_rows .= '<tr>'
				. '<td style="border:1px solid #000;padding:4px 6px;text-align:center;">' . ( (int) $i + 1 ) . '</td>'
				. '<td style="border:1px solid #000;padding:4px 6px;">' . esc_html( (string) ( $p['id_number'] ?? '' ) ?: '—' ) . '</td>'
				. '<td style="border:1px solid #000;padding:4px 6px;">' . esc_html( mb_strtoupper( (string) $p['full_name'], 'UTF-8' ) ) . '</td>'
				. '<td style="border:1px solid #000;padding:4px 6px;">' . esc_html( Datvetau_Booking_Admin_Format::date_to_display( (string) $p['birth_date'] ) ) . '</td>'
				. '<td style="border:1px solid #000;padding:4px 6px;">' . esc_html( (string) ( $p['hometown'] ?? '' ) ?: '—' ) . '</td>'
				. '<td style="border:1px solid #000;padding:4px 6px;">' . esc_html( (string) $p['nationality'] ) . '</td>'
				. '<td style="border:1px solid #000;padding:4px 6px;">' . esc_html( Datvetau_Booking_Admin_Format::fare_category_label( (string) $p['fare_category'] ) ) . '</td>'
				. '<td style="border:1px solid #000;padding:4px 6px;text-align:right;">' . esc_html( number_format_i18n( $line_total ) ) . '</td>'
				. '</tr>';
		}

		$note_block = '';
		if ( ! empty( $booking['booker_note'] ) ) {
			$note_block = '<div style="margin:8px 0;">'
				. esc_html__( 'Ghi chú', 'datvetaucaotoc-booking' ) . ': '
				. esc_html( (string) $booking['booker_note'] )
				. '</div>';
		}

		$detail_url = esc_url( admin_url( 'admin.php?page=datvetau-booking&booking_id=' . (int) $booking['id'] ) );
		$hr         = '<div style="margin:10px 0;color:#666;">-------------------------</div>';

		$html = '<div style="font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#111;line-height:1.45;max-width:960px;">'
			. '<p style="margin:0 0 8px;font-weight:700;font-size:15px;">'
			. esc_html__( 'THÔNG TIN KHÁCH ĐẶT VÉ MỚI:', 'datvetaucaotoc-booking' )
			. '</p>'
			. '<p style="margin:0 0 4px;">'
			. esc_html__( 'Mã đơn', 'datvetaucaotoc-booking' ) . ': '
			. '<span style="background:#fff3cd;padding:1px 4px;">' . $code . '</span>'
			. '</p>'
			. $hr
			. '<p style="margin:4px 0;">* ' . esc_html__( 'Tên liên hệ', 'datvetaucaotoc-booking' ) . ': '
			. '<span style="color:#c00;font-weight:600;">' . $booker_name . '</span></p>'
			. '<p style="margin:4px 0;">* ' . esc_html__( 'Số điện thoại / zalo', 'datvetaucaotoc-booking' ) . ': '
			. '<span style="color:#c00;font-weight:600;">' . $booker_phone . '</span></p>'
			. '<p style="margin:4px 0;">* ' . esc_html__( 'Email', 'datvetaucaotoc-booking' ) . ': ' . $booker_email . '</p>'
			. $hr
			. '<p style="margin:4px 0;"><strong>' . esc_html__( 'Chuyến đi', 'datvetaucaotoc-booking' ) . ':</strong> ' . $route_label . '</p>'
			. '<p style="margin:4px 0;"><strong>' . esc_html__( 'Ngày đi', 'datvetaucaotoc-booking' ) . ':</strong> '
			. esc_html( self::format_trip_date_line( $outbound ) ) . '</p>'
			. '<p style="margin:4px 0;"><strong>' . esc_html__( 'Ngày về', 'datvetaucaotoc-booking' ) . ':</strong> '
			. esc_html( $inbound ? self::format_trip_date_line( $inbound ) : '—' ) . '</p>'
			. '<p style="margin:4px 0;"><strong>' . esc_html__( 'Loại vé', 'datvetaucaotoc-booking' ) . ':</strong> ' . $trip_type . '</p>'
			. '<p style="margin:4px 0;"><strong>' . esc_html__( 'Số lượng', 'datvetaucaotoc-booking' ) . ':</strong> ' . (int) $total . '</p>'
			. $qty_lines
			. $note_block
			. $hr
			. '<p style="margin:8px 0 6px;font-weight:700;">' . esc_html__( 'Thông tin hành khách:', 'datvetaucaotoc-booking' ) . '</p>'
			. '<table style="border-collapse:collapse;width:100%;max-width:960px;font-size:13px;margin:0 0 12px;">'
			. '<thead><tr>'
			. '<th style="border:1px solid #000;padding:4px 6px;background:#f5f5f5;">STT</th>'
			. '<th style="border:1px solid #000;padding:4px 6px;background:#f5f5f5;">CCCD</th>'
			. '<th style="border:1px solid #000;padding:4px 6px;background:#f5f5f5;">' . esc_html__( 'Họ và tên', 'datvetaucaotoc-booking' ) . '</th>'
			. '<th style="border:1px solid #000;padding:4px 6px;background:#f5f5f5;">' . esc_html__( 'Năm sinh', 'datvetaucaotoc-booking' ) . '</th>'
			. '<th style="border:1px solid #000;padding:4px 6px;background:#f5f5f5;">' . esc_html__( 'Quê quán', 'datvetaucaotoc-booking' ) . '</th>'
			. '<th style="border:1px solid #000;padding:4px 6px;background:#f5f5f5;">' . esc_html__( 'Quốc tịch', 'datvetaucaotoc-booking' ) . '</th>'
			. '<th style="border:1px solid #000;padding:4px 6px;background:#f5f5f5;">' . esc_html__( 'Loại vé', 'datvetaucaotoc-booking' ) . '</th>'
			. '<th style="border:1px solid #000;padding:4px 6px;background:#f5f5f5;">' . esc_html__( 'Thành tiền', 'datvetaucaotoc-booking' ) . '</th>'
			. '</tr></thead><tbody>' . $table_rows . '</tbody></table>'
			. '<p style="margin:8px 0 0;"><strong>' . esc_html__( 'Tổng tiền', 'datvetaucaotoc-booking' ) . ':</strong> '
			. '<span style="color:#c00;font-weight:700;">' . $total_fmt . '</span></p>'
			. '<p style="margin:14px 0 0;font-size:12px;color:#555;">'
			. '<a href="' . $detail_url . '">' . esc_html__( 'Xem trong admin', 'datvetaucaotoc-booking' ) . '</a>'
			. '</p>'
			. '</div>';

		return $html;
	}

	/**
	 * @param array<string,mixed>|null $trip
	 */
	private static function format_trip_date_line( ?array $trip ): string {
		if ( ! $trip ) {
			return '—';
		}
		$date = Datvetau_Booking_Admin_Format::date_to_display( (string) $trip['trip_date'] );
		$dep  = substr( (string) $trip['departure_time'], 0, 5 );
		$arr  = substr( (string) $trip['arrival_time'], 0, 5 );
		$op   = (string) ( $trip['operator_name'] ?? '' );
		$line = $date . ' (' . $dep . ' → ' . $arr . ')';
		if ( '' !== $op ) {
			$line .= ' — ' . $op;
		}
		return $line;
	}

	/**
	 * @param array<int,array<string,mixed>> $passengers
	 * @return array{adult:int,child:int,senior:int}
	 */
	private static function fare_counts( array $passengers ): array {
		$counts = array( 'adult' => 0, 'child' => 0, 'senior' => 0 );
		foreach ( $passengers as $p ) {
			$cat = (string) ( $p['fare_category'] ?? 'adult' );
			if ( isset( $counts[ $cat ] ) ) {
				++$counts[ $cat ];
			}
		}
		return $counts;
	}
}
