<?php

namespace App\Notifications;

use App\Channels\WhatsAppChannel;
use App\Models\NotificationSetting;
use App\Models\Order;
use App\Models\WhatsappNotificationSetting;

class SendOrderBill extends BaseNotification
{

    protected $order;
    protected $settings;
    protected $notificationSetting;
    protected $whatsappNotificationSetting;

    /**
     * Create a new notification instance.
     *
     * @param $order
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->settings = $order->branch->restaurant;
        $this->notificationSetting = NotificationSetting::where('type', 'order_bill_sent')->where('restaurant_id', $order->branch->restaurant_id)->first();
        $this->whatsappNotificationSetting = WhatsappNotificationSetting::where('type', 'order_bill_sent')->first();
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param mixed $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        $channels = [];

        if ($this->notificationSetting->send_email == 1 && !empty($notifiable->email)) {
            $channels[] = 'mail';
        }

        if ($this->whatsappNotificationSetting->active && !empty($notifiable->phone)) {
            $channels[] = WhatsAppChannel::class;
        }

        return $channels;
    }


    /**
     * Get the mail representation of the notification.
     *
     * @param mixed $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        // Calculate tax amounts
        $taxesWithAmount = [];

        foreach ($this->order->taxes as $tax) {
            $taxAmount = $this->order->sub_total * ($tax->tax->tax_percent / 100);
            $taxesWithAmount[] = [
                'name' => $tax->tax->tax_name,
                'amount' => $taxAmount,
                'rate' => $tax->tax->tax_percent,
            ];
        }

        $chargesWithAmount = [];

        foreach ($this->order->charges as $charge) {

            $chargeAmount = $charge->charge->charge_type == 'percent' ? ($charge->charge->charge_value / 100) * $this->order->sub_total : $charge->charge->charge_value;
            $chargesWithAmount[] = [
                'name' => $charge->charge->charge_name,
                'amount' => $chargeAmount,
                'rate' => $charge->charge->charge_value,
                'type' => $charge->charge->charge_type,
            ];
        }

        $build = parent::build($notifiable);
        return $build
    ->subject(__('email.sendOrderBill.subject', [
        'order_number' => $this->order->order_number,
        'site_name' => $this->settings->name
    ]))
    ->markdown('emails.order-bill', [
        'order' => $this->order,
        'subtotal' => $this->order->sub_total,
        'taxesWithAmount' => $taxesWithAmount,
        'chargesWithAmount' => $chargesWithAmount,
        'totalPrice' => $this->order->total,
        'items' => $this->order->items,
        'settings' => $this->settings,
        'taxMode' => $this->order->restaurant->tax_mode ?? 'exclusive', // 👈 add this line
    ]);
    }


    public function toWhatsApp($notifiable)
    {
        $template = $this->whatsappNotificationSetting->body;

        // Format taxes
        $taxesWithAmount = [];
        foreach ($this->order->taxes as $tax) {
            $taxAmount = $this->order->sub_total * ($tax->tax->tax_percent / 100);
            $taxesWithAmount[] = "{$tax->tax->tax_name}: " . currency_format($taxAmount, $this->settings->currency_id);
        }

        // Format charges
        $chargesWithAmount = [];
        foreach ($this->order->charges as $charge) {
            $chargeAmount = $charge->charge->charge_type == 'percent'
                ? ($charge->charge->charge_value / 100) * $this->order->sub_total
                : $charge->charge->charge_value;
            $chargesWithAmount[] = "{$charge->charge->charge_name}: " . currency_format($chargeAmount, $this->settings->currency_id);
        }

        // Format items
        $orderSummary = $this->order->items->map(function ($item) {
            return $item->quantity . ' x ' . $item->menuItem->item_name  . ' @ ' . currency_format($item->price, $this->settings->currency_id);
        })->implode("\n");

        // Combine extras (taxes + charges)
        $extraCharges = implode("\n", array_merge($taxesWithAmount, $chargesWithAmount));

        // Replace placeholders in the template
        $placeholders = [
            '__customer_name__'   => $this->order->customer->name,
            '__order_number__'    => $this->order->order_number,
            '__order_type__'      => $this->order->order_type,
            '__items__'           => $orderSummary . (!empty($extraCharges) ? "\n" . $extraCharges : ''),
            '__total__'           => currency_format($this->order->total, $this->settings->currency_id),
            '__order_time__'      => $this->order->created_at->format('d M Y, h:i A'),
            '__bill_link__'       => route('order_success', $this->order->id) ?? '',
            '__restaurant_name__' => $this->settings->name ?? 'Our Restaurant',
        ];

        $message = str_replace(array_keys($placeholders), array_values($placeholders), $template);

        return [
            'to' => str_replace("+", '', $this->settings->country->phonecode) . $this->order->customer->phone, // Must include country code
            'message' => $message,
        ];
    }




    /**
     * Format order items for the email body.
     *
     * @param $items
     * @return string
     */
    protected function formatOrderSummary($items)
    {
        return $items->map(function ($item) {
            return $item->quantity . ' x ' . $item->name . ' @ ' . currency_format($item->price, $this->settings->currency_id);
        })->implode(', ');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param mixed $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'order_id' => $this->order->id,
            'customer_name' => $this->order->customer->name,
            'table_id' => $this->order->table_id,
            'total_price' => $this->order->total_price,
        ];
    }
}
