<?php

namespace App\Livewire;

use App\Livewire\Concerns\ResolvesCustomer;
use App\Models\Order;
use App\Services\Billing\CustomDomainAccess;
use LivewireUI\Modal\ModalComponent;

/**
 * Taking a not-yet-paid purchase back out of the cart.
 *
 * Scoped to the signed-in customer's own orders: modals are reachable without
 * the page's own guards, so the ownership check belongs here, not in the view
 * that happens to link to it.
 */
class ConfirmRemoveOrder extends ModalComponent
{
    use ResolvesCustomer;

    public string $uuid;

    public string $label = '';

    public int $amountCents = 0;

    public function mount(string $uuid): void
    {
        $order = $this->order($uuid);
        abort_if($order === null, 404);

        $this->uuid = $uuid;
        $this->label = $order->label();
        $this->amountCents = $order->amount_cents;
    }

    public function remove(): void
    {
        $order = $this->order($this->uuid);

        // Gone or already paid for: say so instead of pretending it worked.
        if ($order === null) {
            $this->dispatch('notify', message: __('billing.cart.gone'));
            $this->closeModal();

            return;
        }

        // A downgrade is booked in two places — the cart entry the customer can
        // see, and the date stamped on the contract that actually carries it
        // out. Taking the entry back out has to unbook it, or the package would
        // shrink at the end of the term for a request the customer had already
        // withdrawn, with nothing left on the page to explain why.
        if ($order->type === 'downgrade') {
            $contract = app(CustomDomainAccess::class)->contractOf($this->customer());

            if ($contract?->pending_plan === $order->plan) {
                $contract->clearPendingPlanChange();
            }
        }

        $order->delete();

        $this->dispatch('order-removed');
        $this->closeModal();
    }

    /** @return Order|null the customer's own, still-pending order */
    private function order(string $uuid): ?Order
    {
        $customer = $this->customer();
        if ($customer === null) {
            return null;
        }

        return Order::query()
            ->where('customer_id', $customer->id)
            ->where('uuid', $uuid)
            ->where('status', 'pending')
            ->first();
    }

    public function render()
    {
        return view('livewire.confirm-remove-order');
    }
}
