<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Voucher;
use App\Models\Cart;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class CheckoutVoucher extends Component
{
    public $voucherCode;
    public $message;
    public $discountAmount = 0;
    public $subtotal;
    public $taxSubtotal;
    public $shippingPrice;
    public $taxAmount = 0;
    public $finalTotal = 0;
    public $cartTotal = 0; // Keep cartTotal as it's used for voucher min_spend and discount calculation

    public function mount($subtotal, $shippingPrice, $taxSubtotal = null)
    {
        $this->subtotal = $subtotal;
        $this->taxSubtotal = $taxSubtotal ?? $subtotal;
        $this->shippingPrice = $shippingPrice;
        $this->calculateTotal();
    }

    public function calculateTotal()
    {
        // The subtotal and shippingPrice are now passed via mount, so no need to recalculate from cart
        // The original calculateTotal logic for fetching cart items and calculating subtotal/shippingPrice is removed.

        $this->taxAmount = 0; // Reset tax amount before recalculating
        $this->cartTotal = $this->subtotal; // cartTotal always reflects the selling price (product_price)

        if (Auth::check() && Auth::user()->is_corporate) {
            // Tax is calculated based on system setting percentage of the tax subtotal (using cutted prices)
            $taxRate = (float) \App\Models\SystemSetting::get('corporate_tax_percentage', 18.00);
            $this->taxAmount = round(($this->taxSubtotal * $taxRate) / 100, 2);
        }
        $this->finalTotal = $this->cartTotal + $this->shippingPrice + $this->taxAmount - $this->discountAmount;
    }

    public function applyVoucher()
    {
        $this->message = '';
        $voucher = Voucher::where('code', $this->voucherCode)->first();
        if (!$voucher) {
            $this->message = 'Invalid Voucher Code';
            $this->discountAmount = 0;
            $this->calculateTotal();
            return;
        }

        if (!$voucher->isValid()) {
             $this->message = 'Voucher is inactive or expired';
             $this->discountAmount = 0;
             $this->calculateTotal();
             return;
        }

        if ($voucher->redeemed_by !== null) {
             $this->message = 'This voucher has already been redeemed';
             $this->discountAmount = 0;
             $this->calculateTotal();
             return;
        }

        if (!Auth::check()) {
            $this->message = 'Login is required to use a voucher.';
            $this->discountAmount = 0;
            $this->calculateTotal();
            return;
        }

        $alreadyUsed = \App\Models\Order::where('userid', Auth::id())
            ->where('voucher_code', $this->voucherCode)
            ->exists();

        if ($alreadyUsed) {
            $this->message = 'You have already used this voucher code.';
            $this->discountAmount = 0;
            $this->calculateTotal();
            return;
        }
        $orderTotal = $this->cartTotal + $this->shippingPrice + $this->taxAmount;
        if ($orderTotal < $voucher->min_spend) {
            $this->message = "Minimum spend of LKR " . number_format($voucher->min_spend, 2) . " required";
            $this->discountAmount = 0;
            $this->calculateTotal();
            return;
        }

        if ($voucher->type == 'fixed') {
            $this->discountAmount = $voucher->value;
        } else {
            $this->discountAmount = ($this->cartTotal * $voucher->value) / 100;
        }

        // Validate discount isn't more than total? (Ideally yes)
        if ($this->discountAmount > $this->cartTotal) {
            $this->discountAmount = $this->cartTotal;
        }

        $this->finalTotal = $this->cartTotal + $this->shippingPrice + $this->taxAmount - $this->discountAmount;
        
        $this->message = 'Voucher Applied: ' . $voucher->code;
        
        $this->dispatch('voucher-applied', [
            'discount' => $this->discountAmount,
            'code' => $voucher->code,
            'newTotal' => $this->finalTotal
        ]);
    }

    public function removeVoucher()
    {
        $this->voucherCode = '';
        $this->discountAmount = 0;
        $this->message = '';
        $this->calculateTotal();
        
        $this->dispatch('voucher-removed', [
            'newTotal' => $this->finalTotal
        ]);
    }

    public function render()
    {
        return view('livewire.checkout-voucher');
    }
}
