<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;

class Supplier extends Model
{
    use HasFactory;

    protected $hidden = ['user_id'];

    private static function saveBasicInfo($supplier, $request)
    {
        $supplier->medicine_company_id = $request->medicine_company_id;
        $supplier->supplier_name = $request->supplier_name;
        $supplier->supplier_email = $request->supplier_email;
        $supplier->supplier_phone = $request->supplier_phone;
        $supplier->save();

        return $supplier;
    }

    public static function newSupplier($request)
    {
        $supplier = new self;
        $supplier->user_id = Auth::id();
        $supplier->status = '1';

        return self::saveBasicInfo($supplier, $request);
    }

    public static function change_status($id): string
    {
        $supplier = self::query()->find($id);
        if ($supplier->status == '1') {
            $supplier->status = '0';
            $message = 'Inactive successfully!';
        } else {
            $supplier->status = '1';
            $message = 'Active successfully!';
        }
        $supplier->save();

        return $message;
    }

    public static function updateSupplier($request, $id)
    {
        return self::saveBasicInfo(self::query()->find($id), $request);
    }

    public function medicineCompany(): BelongsTo
    {
        return $this->belongsTo(MedicineCompany::class, 'medicine_company_id', 'id');
    }
}
