<?php

namespace App\Models;

class TimeOffRequestModel extends TenantModel
{
    protected $table         = 'time_off_requests';
    protected $primaryKey    = 'id';
    protected $returnType    = 'object';
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = '';

    protected $allowedFields = [
        'user_id',
        'date_from',
        'date_to',
        'reason',
        'status',
        'reviewed_by',
        'reviewed_at',
    ];

    public function withDetails()
    {
        return $this->select('time_off_requests.*, users.full_name as staff_name')
            ->join('users', 'users.id = time_off_requests.user_id', 'left');
    }

    public function pending(): array
    {
        return $this->withDetails()->where('time_off_requests.status', 'pending')->orderBy('time_off_requests.created_at')->findAll();
    }

    public function pendingCount(): int
    {
        return $this->where('status', 'pending')->countAllResults();
    }

    public function forUser(int $userId): array
    {
        return $this->where('user_id', $userId)->orderBy('date_from', 'desc')->findAll();
    }

    /** Used by ShiftController::assign() to warn/block scheduling someone during their approved leave. */
    public function hasApprovedOverlap(int $userId, string $date): bool
    {
        return $this->where('user_id', $userId)
            ->where('status', 'approved')
            ->where('date_from <=', $date)
            ->where('date_to >=', $date)
            ->countAllResults() > 0;
    }
}
