<?php

namespace App\Models;

use App\Traits\HasFile;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Attributes\UsePolicy;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class PreInvoice extends Model
{
    use HasFactory, HasFile;

    protected $fillable = [
        'creator_id',
        'title',
        'customer_name',
        'company_name',
        'selected_quote_id',
        'email',
        'phone',
        'address',
        'city',
        'postal_code',
        'is_paid',
        'paid_amount',
        'status',
        'notes',
        'options',
    ];

    protected $with = ['creator', 'items', 'quotes.items'];
    public function creator()
    {
        return $this->belongsTo(User::class, 'creator_id');
    }

    public function items()
    {
        return $this->hasMany(PreInvoiceItem::class);
    }

    public function quotes()
    {
        return $this->hasMany(Quote::class);
    }

    // Helpers
    public function getTotalEstimatedAttribute()
    {
        return $this->items->sum(fn($i) => $i->estimated_price * $i->qty);
    }

    public function createCompressionQuote(): array
    {
        // Get all quotes for this pre-invoice (to learn which suppliers are involved)
        $quotes = Quote::with('supplier')
            ->where('pre_invoice_id', $this->id)
            ->get();

        // Suppliers (aka sellers) list
        $suppliers = $quotes
            ->pluck('supplier')
            ->filter()
            ->unique('id')
            ->values();

        // Map supplier_id -> quote_id for fast lookups
        $supplierToQuoteId = $quotes->mapWithKeys(
            fn($q) => [$q->supplier_id => $q->id]
        );

        // Ensure items have their quoteItems eager loaded in the controller:
        // PreInvoice::with(['items.quoteItems'])->findOrFail($id);
        $rows = [];
        foreach ($this->items as $item) {
            // Group this item's quoteItems by quote_id for O(1) access
            $qiByQuote = $item->quoteItems->keyBy('quote_id');

            $row = [
                'item_id'   => $item->id,
                'item_name' => $item->name ?? ('Item #' . $item->id),
                'sellers'   => [], // one entry per supplier column
            ];

            foreach ($suppliers as $supplier) {
                $quoteId    = $supplierToQuoteId[$supplier->id] ?? null;
                $quoteItem  = $quoteId ? ($qiByQuote[$quoteId] ?? null) : null;

                $row['sellers'][] = [
                    'supplier_id'   => $supplier->id,
                    'supplier_name' => $supplier->name ?? ('Supplier #' . $supplier->id),
                    'price'         => $quoteItem?->price,  // null if missing
                    'qty'           => $quoteItem?->qty,
                    'quote_item_id' => $quoteItem?->id,
                ];
            }

            $rows[] = $row;
        }

        return [
            'headers' => $suppliers->map(fn($s) => [
                'id'   => $s->id,
                'name' => $s->name ?? ('Supplier #' . $s->id),
            ])->values()->all(),
            'rows' => $rows,
        ];
    }

    // Scopes
    public function scopePaid($query)
    {
        return $query->where('is_paid', true);
    }

    public function scopeFilter($query, $filters)
    {

        // creator_id
        if (isset($filters['creator'])) {
            $query->where('creator_id', $filters['creator_id']);
        }
        // company_name
        if (isset($filters['company_name'])) {
            $query->where('company_name', $filters['company_name']);
        }
        // email
        if (isset($filters['email'])) {
            $query->where('email', $filters['email']);
        }
        // phone
        if (isset($filters['phone'])) {
            $query->where('phone', $filters['phone']);
        }
        // city
        if (isset($filters['city'])) {
            $query->where('city', $filters['city']);
        }
        // status
        if (isset($filters['status'])) {
            $query->where('status', $filters['status']);
        }
        // is_paid
        if (isset($filters['is_paid'])) {
            $query->where('is_paid', $filters['is_paid']);
        }

        return $query;
    }
}
