<?php

namespace App\Models;

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

    protected $allowedFields = [
        'requesting_shift_id',
        'requested_by',
        'target_user_id',
        'reason',
        'status',
        'reviewed_by',
        'reviewed_at',
    ];

    public function withDetails()
    {
        return $this->select("shift_swap_requests.*,
                shifts.shift_date as shift_date, shifts.shift_block as shift_block,
                requester.full_name as requester_name, target.full_name as target_name")
            ->join('shifts', 'shifts.id = shift_swap_requests.requesting_shift_id', 'left')
            ->join('users requester', 'requester.id = shift_swap_requests.requested_by', 'left')
            ->join('users target', 'target.id = shift_swap_requests.target_user_id', 'left');
    }

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

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

    public function forUser(int $userId): array
    {
        return $this->withDetails()
            ->groupStart()
                ->where('shift_swap_requests.requested_by', $userId)
                ->orWhere('shift_swap_requests.target_user_id', $userId)
            ->groupEnd()
            ->orderBy('shift_swap_requests.created_at', 'desc')
            ->findAll();
    }
}
