<?php

namespace App\Models;

use App\Models\AssignedWorkers;
use App\Models\ProjectSupervisors;
use Illuminate\Support\Facades\DB;

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

class Projects extends Model
{
    use HasFactory, SoftDeletes;
	protected $table = 'projects';
    protected $fillable = [
        'company_id',
        'project_manager_id',
        'name',
        'description',
        'additional_info',
        'location',
        'worker_items',
        'clock_in',
        'clock_out',
        'date_start',
        'date_end',
        'created_by',
    ];

    public function project_supervisors()
    {
        return $this->hasMany(ProjectSupervisors::class, 'project_id', 'id')
            ->join('workers', 'workers.id', '=', 'project_supervisors.user_id')
            ->orderBy('date_from', 'asc')
            ->orderBy('date_to', 'asc');
    }

    public function assigned_employees()
    {
        return $this->hasMany(AssignedWorkers::class, 'project_id', 'id')
            ->join('assigned_availability', 'assigned_availability.assigned_worker_id', '=', 'assigned_workers.id')
            ->join('workers as worker', 'worker.id', '=', 'assigned_workers.worker_id')
            ->join('availabilities', 'availabilities.id', '=', 'assigned_availability.availability_id')
            ->join('worker_experiences', 'worker_experiences.worker_id', '=', 'assigned_workers.worker_id')
            ->join('company_experiences', 'company_experiences.id', '=', 'worker_experiences.experience_id')
            ->where('worker_experiences.is_worker', true);
    }

    //** belongsTo, belongsToMany, hasOne, hasMany relationships */ 

    /**
     * Fetch Company belongsTo relationship. 
     * 
     * // @return ? 
     */
    public function company() // : ? 
    {
        return $this->belongsTo(
            related: Company::class,
            foreignKey: "company_id",
            ownerKey: "id",
            relation: "company"
        );
    }
}
