<?php

namespace App\Models;

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

class Project extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name', 'reference', 'address', 'country', 'lat', 'lng',
        'start_date', 'end_date_estimated', 'status', 'created_by',
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date_estimated' => 'date',
    ];

    public function changeOrders()
    {
        return $this->hasMany(ChangeOrder::class);
    }

    // Relationships
    public function phases()
    {
        return $this->hasMany(Phase::class)->orderBy('order');
    }

    public function layers()
    {
        return $this->hasMany(Layer::class);
    }

    public function users()
    {
        return $this->belongsToMany(User::class)->withPivot('role_in_project');
    }

    public function companies()
    {
        return $this->belongsToMany(Company::class, 'company_project')
            ->withPivot('role_in_project')
            ->withTimestamps();
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function media()
    {
        return $this->morphMany(Media::class, 'mediable');
    }

    /** Plantillas de inspección asignadas a este proyecto (catálogo global ↔ pivot). */
    public function inspectionTemplates()
    {
        return $this->belongsToMany(InspectionTemplate::class, 'inspection_template_project')->withTimestamps();
    }

    public function images()
    {
        return $this->morphMany(Media::class, 'mediable')->where('category', 'image');
    }

    public function tasks()
    {
        return $this->hasMany(Task::class);
    }

    // Scope to filter accessible projects for non-admin users
    public function scopeAccessibleBy($query, User $user)
    {
        if ($user->can('manage all')) {
            return $query;
        }

        return $query->whereHas('users', function ($q) use ($user) {
            $q->where('user_id', $user->id);
        });
    }
}
