<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\BaseModel;

class StoreOrder extends BaseModel
{
    use HasFactory;

    protected $table = 'store_order';

    public function user(){
        return $this->hasOne(User::class, 'id', 'user_id');
    }
    public function client(){
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    
    public function paymentMethod(){
        return $this->hasOne(PaymentMethod::class, 'id', 'payment_method_id');
    }
    public function financialTransactions(){
        return $this->hasMany(FinancialTransaction::class, 'order_id', 'id');
    }
    public function finalFinancialTransaction(){
        return FinancialTransaction::where('order_id', $this->id)->orderBy('created_at', 'DESC')->first();
    }

    public function orderNumber() {
        if ($this->iid) return $this->iid;
        return getFirstSectionUID($this->uid);
    }

    public function tests(){
        $detail = json_decode($this->detail_json);
        $selectedOptions = json_decode(@$detail->selected_options);
        if(!$selectedOptions) return null;
        return (array) @$selectedOptions->tests;
    }


    public function total(){
        $detail = json_decode($this->detail_json);
        $selectedOptions = json_decode(@$detail->selected_options);
        if(!$selectedOptions) return 0;
        return floatval(@$selectedOptions->tests_total);
    }

    public function lab(){
        $detail = json_decode($this->detail_json);
        $selectedOptions = json_decode(@$detail->selected_options);
        $labID = @$selectedOptions->tests_lab_id;
        if(!$labID) return null;
        return Lab::where('id', $labID)->first();
    }

    public function createdByUser(){
        return $this->hasOne(User::class, 'id', 'created_by_user_id');
    }
    
}
