<?php

namespace App\Models\Warehouse;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class Project extends Model
{
    use HasFactory;

    protected $fillable = [
        'project_number',
        'project_name',
        'project_division_id',
        'external_project_id',
        'project_id',
        'last_synced_at',
    ];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'last_synced_at' => 'datetime'
    ];

    /**
     * Relationship: A project belongs to a division
     */
    public function projectDivision()
    {
        return $this->belongsTo(ProjectDivision::class, 'project_division_id');
    }

    /**
     * Scope for searching projects by name or number.
     */
    public function scopeSearch($query, $search)
    {
        if (empty($search)) {
            return $query;
        }

        return $query->where(function ($q) use ($search) {
            $q->where('project_name', 'LIKE', "%{$search}%")
              ->orWhere('project_number', 'LIKE', "%{$search}%");
        });
    }

    /**
     * Apply active filtering only for project schemas that support it.
     */
    public function scopeActive($query)
    {
        if (Schema::hasColumn($this->getTable(), 'status')) {
            return $query->where('status', 'active');
        }

        return $query;
    }

    /**
     * Generate unique project number
     */
    public static function generateProjectNumber($divisionId = null)
    {
        $prefix = 'PRJ';

        if ($divisionId) {
            $division = ProjectDivision::find($divisionId);
            if ($division) {
                $prefix = strtoupper(substr($division->division_code, 0, 3));
            }
        }

        $year = now()->format('Y');
        $sequence = str_pad(self::whereYear('created_at', $year)->count() + 1, 4, '0', STR_PAD_LEFT);

        return $prefix . $year . $sequence;
    }
}
