<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Department extends Model
{
    use HasFactory, SoftDeletes;

    protected $guarded = [];
    protected $table = 'test_departments';

    public function testPackages()
    {
        return $this->hasMany(TestPackage::class);
    }

    public function doctorSignature()
    {
        return $this->hasMany(SignaturePermission::class, 'test_departments_id', 'id')->with('signature');
    }

    static public function getDepartmentWithSignature($where = [])
    {
        return self::select([
                'test_departments.id',
                'test_departments.name',
                'test_departments.show_in_report',
                'test_departments.show_report_heading',
                'doc_signature.max_height',
                'doc_signature.max_width',
                'doc_signature.signature as doc_signature',
                'tech_signature.signature as tech_signature',
                'doc_signature.max_height as doc_max_height',
                'doc_signature.max_width as doc_max_width',
                'tech_signature.max_height as tech_max_height',
                'tech_signature.max_width as tech_max_width',
            ])
            ->leftjoin('signature_permissions as doc_signature_perm', function ($join) {
                $join->on('test_departments.id', '=', 'doc_signature_perm.test_departments_id')
                    ->whereIn('doc_signature_perm.signatures_id', function ($query) {
                        $query->select('id')
                           ->from('signatures')
                           ->where('signature_for', '=', 'Doctor')
                           ->where('status', '=', '1')
                           ->get()->pluck('id');
                    });
            })
            ->leftjoin('signature_permissions as tech_signature_perm', function ($join) {
                $join->on('test_departments.id', '=', 'tech_signature_perm.test_departments_id')
                     ->whereIn('tech_signature_perm.signatures_id', function ($query) {
                         $query->select('id')
                           ->from('signatures')
                           ->where('signature_for', '=', 'Technician')
                           ->where('status', '=', '1')
                           ->get()->pluck('id');
                     });
            })
            ->leftjoin('signatures as doc_signature', 'doc_signature.id', 'doc_signature_perm.signatures_id')
            ->leftjoin('signatures as tech_signature', 'tech_signature.id', 'tech_signature_perm.signatures_id')
            ->where($where)
            ->first();
    }
}
