<?php

namespace App\Mail;

use App\Laravue\Models\User;
use App\Product;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;

/**
 * Email gửi sau khi admin approve xác thực danh tính
 * Chứa TẤT CẢ đơn hàng của user (không gửi riêng lẻ)
 *
 * Tất cả logic tính toán được xử lý trong Mail class,
 * template chỉ việc hiển thị dữ liệu đã được chuẩn bị sẵn.
 */
class IdentityVerificationApprovedWithOrders extends Mailable implements ShouldQueue
{
	use Queueable, SerializesModels;

	public $user;
	public $orders;
	public $orderResults;

	/**
	 * Create a new message instance.
	 *
	 * @param User $user
	 * @param Collection $orders Collection of Order models
	 * @param array $orderResults Kết quả xử lý từng order (payment success/failed)
	 * @return void
	 */
	public function __construct(User $user, Collection $orders, array $orderResults = [])
	{
		$this->user = $user;
		$this->orders = $orders;
		$this->orderResults = $orderResults;
		$this->onConnection(config('queue.default'));
		$this->onQueue(config('queue.connections.redis.queue'));
	}

	/**
	 * Build the message.
	 *
	 * @return $this
	 */
	public function build()
	{
		$siteName = config('settings.site_name', 'KIREI');
		$siteUrl = config('app.url');

		// Subject theo yêu cầu khách hàng
		$subject = "ご注文が確定しました。「{$siteName}」(着物レンタル）";

		// Load rental config
		$paymentDeadlineDays = (int) config('rental_dates.payment_deadline_days', 11);
		$storeShippingDays = (int) config('rental_dates.store_shipping_days', 10);
		$productDeliveryDays = (int) config('rental_dates.product_delivery_days', 3);
		$returnAfterDays = (int) config('rental_dates.return_after_days', 1);
		$storeArrivalAfterReturnDays = (int) config('rental_dates.store_arrival_after_return_days', 1);
		$defaultRentalNights = (int) config('rental_dates.default_rental_nights', 5);

		// Tính toán dữ liệu header (từ order đầu tiên)
		$firstOrder = $this->orders->first();
		$firstOrderDetail = $firstOrder ? $firstOrder->order_detail->first() : null;
		$firstWearingDate = null;
		$firstPaymentDeadline = '未定';

		if ($firstOrderDetail && $firstOrderDetail->wear_date) {
			$firstWearingDate = Carbon::parse($firstOrderDetail->wear_date)->format('Y/m/d');
			$firstPaymentDeadline = Carbon::parse($firstOrderDetail->wear_date)
				->subDays($paymentDeadlineDays)
				->format('Y/m/d');
		}

		// Tính tổng tiền tất cả orders
		$grandTotal = number_format($this->orders->sum('total_price'));

		// Xử lý dữ liệu cho từng order
		$ordersData = [];
		foreach ($this->orders as $index => $order) {
			$ordersData[] = $this->prepareOrderData(
				$order,
				$index,
				$paymentDeadlineDays,
				$storeShippingDays,
				$productDeliveryDays,
				$returnAfterDays,
				$storeArrivalAfterReturnDays,
				$defaultRentalNights
			);
		}

		return $this->from(config('mail.from.address'), config('mail.from.name'))
			->replyTo(config('mail.from.address'), config('mail.from.name'))
			->subject($subject)
			->view('emails.identity-verification.approved-with-orders')
			->with([
				// User info
				'userName'             => $this->user->full_name ?? $this->user->name,

				// Site info
				'siteName'             => $siteName,
				'siteUrl'              => $siteUrl,

				// Header data (từ order đầu tiên)
				'firstWearingDate'     => $firstWearingDate ?? '未定',
				'firstPaymentDeadline' => $firstPaymentDeadline,
				'grandTotal'           => $grandTotal,
				'paymentDeadlineDays'  => $paymentDeadlineDays,

				// Orders data (đã xử lý sẵn)
				'ordersData'           => $ordersData,
				'ordersCount'          => count($ordersData),

				// Rental config (để hiển thị số ngày)
				'defaultRentalNights'  => $defaultRentalNights,
			]);
	}

	/**
	 * Chuẩn bị dữ liệu cho một order
	 *
	 * @param mixed $order
	 * @param int $index
	 * @param int $paymentDeadlineDays
	 * @param int $storeShippingDays
	 * @param int $productDeliveryDays
	 * @param int $returnAfterDays
	 * @param int $storeArrivalAfterReturnDays
	 * @param int $defaultRentalNights
	 * @return array
	 */
	protected function prepareOrderData(
		$order,
		$index,
		$paymentDeadlineDays,
		$storeShippingDays,
		$productDeliveryDays,
		$returnAfterDays,
		$storeArrivalAfterReturnDays,
		$defaultRentalNights
	): array {
		$orderDetail = $order->order_detail->first();
		$product = $orderDetail ? $orderDetail->product : null;

		// Parse wearing date
		$wearingDate = null;
		if ($orderDetail && $orderDetail->wear_date) {
			$wearingDate = Carbon::parse($orderDetail->wear_date);
		}

		// Tính các ngày liên quan
		$wearingDateFormatted = $wearingDate ? $wearingDate->format('Y/m/d') : '未定';

		// Rental period
		$rentalStartDate = $wearingDate ? $wearingDate->copy()->subDays($productDeliveryDays) : null;
		$rentalEndDate = $rentalStartDate ? $rentalStartDate->copy()->addDays($defaultRentalNights) : null;
		$rentalPeriod = ($rentalStartDate && $rentalEndDate)
			? $rentalStartDate->format('Y/m/d') . ' ～ ' . $rentalEndDate->format('Y/m/d')
			: '未定';

		// Rental flow dates
		$storeShippingDate = $wearingDate
			? $wearingDate->copy()->subDays($storeShippingDays)->format('Y/m/d') . ' 頃'
			: '未定';
		$deliveryDate = $wearingDate
			? $wearingDate->copy()->subDays($productDeliveryDays)->format('Y/m/d')
			: '未定';
		$returnDate = $wearingDate
			? $wearingDate->copy()->addDays($returnAfterDays)->format('Y/m/d')
			: '未定';
		$storeArrivalDate = $wearingDate
			? $wearingDate->copy()->addDays($returnAfterDays + $storeArrivalAfterReturnDays)->format('Y/m/d')
			: '未定';

		// Payment method
		$paymentMethodText = $order->payment_method == 0 ? 'クレジットカード' : '銀行振り込み';

		// Prices
		$productPrice = $orderDetail ? number_format($orderDetail->price ?? 0) : '0';
		$optionPrice = number_format($order->option_price ?? 0);
		$shippingCost = number_format($order->shipping_cost ?? 0);
		$totalPrice = number_format($order->total_price ?? 0);

		// Product code
		$productCode = '';
		if ($product && $product->code) {
			$productCode = $product->code;
		} elseif ($orderDetail && $orderDetail->product_id) {
			$productCode = Product::where('id', $orderDetail->product_id)->value('code') ?? '';
		}

		// Order result
		$orderResult = collect($this->orderResults)->firstWhere('order_id', $order->id);

		return [
			'index'              => $index,
			'orderCode'          => $order->code,
			'wearingDate'        => $wearingDateFormatted,
			'rentalPeriod'       => $rentalPeriod,
			'productCode'        => $productCode,
			'paymentMethod'      => $paymentMethodText,
			'productPrice'       => $productPrice,
			'optionPrice'        => $optionPrice,
			'shippingCost'       => $shippingCost,
			'totalPrice'         => $totalPrice,
			'storeShippingDate'  => $storeShippingDate,
			'deliveryDate'       => $deliveryDate,
			'returnDate'         => $returnDate,
			'storeArrivalDate'   => $storeArrivalDate,
			'orderResult'        => $orderResult,
		];
	}
}
