<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class PosInvoice extends Model
{
    use HasFactory;
    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults();
   }

    protected $fillable = ["location_id","customer_id","sales_id","sales2_id",
        "user_id","time","number",
        "note","subtotal", "voucher", "discount","tax","total",
        "vouchers","canceled_at","canceled_note","canceled_by", "note_internal"];

    public function ticket()
    {
        return $this->hasOne(LuckyWheelTicket::class, 'invoice_id')->with("prize","gets");
    }

    public function customer(){
        return $this->belongsTo(Customer::class);
    }

    public function sales(){
        return $this->belongsTo(Sales::class);
    }

    public function sales2(){
        return $this->belongsTo(Sales::class, 'sales2_id', 'id');
    }

    public function location(){
        return $this->belongsTo(Location::class);
    }

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function details(){
        return $this->hasMany(PosInvoiceDetail::class,"invoice_id")
            ->orderBy("line_no","asc");
    }

    public function payments(){
        return $this->hasMany(PosInvoicePayment::class,"invoice_id");
    }

    public function canceledBy(){
        return $this->belongsTo(User::class,"canceled_by");
    }

    public function vouchers(){
        return $this->morphMany(Voucher::class,'reference_used');
    }

    public function discountVouchers(){
        return $this->hasMany(PosInvoiceVoucher::class, 'pos_invoice_id');
    }

    public function getPoint() {
       $total = CustomerPoint::where('reference_type', 'App\Models\PosInvoice')
        ->where('reference_id', $this->id)
        ->sum('point');

        return $total;
    }

    public function feedback(){
        return $this->hasOne(SurveyFeedback::class,"invoice_id");
    }
}
