<?php

namespace App\Filament\Supplier\Pages;

use App\Models\PurchaseOrder;

class MyPurchaseOrders extends \Filament\Pages\Page
{
    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-clipboard-document-list';

    protected static ?string $navigationLabel = 'أوامر التوريد';

    protected static ?string $title = 'أوامر التوريد الخاصة بي';

    protected static ?int $navigationSort = 1;

    protected string $view = 'filament.supplier.pages.my-purchase-orders';

    protected static bool $shouldRegisterNavigation = true;

    public function getPurchaseOrders()
    {
        $supplier = auth()->user()?->supplier;
        if (! $supplier) {
            return collect();
        }

        return PurchaseOrder::with(['items.variant.product', 'sourceOrder'])
            ->where('supplier_id', $supplier->id)
            ->orderByDesc('created_at')
            ->get();
    }

    public function confirmOrder(int $poId): void
    {
        $supplier = auth()->user()?->supplier;
        if (! $supplier) {
            return;
        }

        $po = PurchaseOrder::where('id', $poId)
            ->where('supplier_id', $supplier->id)
            ->where('status', PurchaseOrder::STATUS_DRAFT)
            ->first();

        if ($po) {
            $po->update(['status' => PurchaseOrder::STATUS_CONFIRMED]);

            \Filament\Notifications\Notification::make()
                ->title('تم تأكيد أمر الشراء بنجاح')
                ->success()
                ->send();
        } else {
            \Filament\Notifications\Notification::make()
                ->title('لم يتم العثور على الأمر أو تم تأكيده مسبقاً')
                ->warning()
                ->send();
        }
    }
}
