<?php

namespace App\Models;

use Config\Lookups;

class ComplaintModel extends TenantModel
{
    protected $table            = 'complaints';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = [
        'guest_id',
        'category',
        'description',
        'priority',
        'status',
        'assigned_to',
        'reported_by',
        'resolution_notes',
        'resolved_at',
        'follow_up_at',
        'follow_up_notes',
    ];

    public function __construct()
    {
        parent::__construct();

        $lookups = new Lookups();

        $this->validationRules = [
            'guest_id'    => 'required|is_natural_no_zero',
            'category'    => 'required|in_list[' . implode(',', array_keys($lookups->complaintCategories)) . ']',
            'description' => 'required',
            'priority'    => 'permit_empty|in_list[' . implode(',', array_keys($lookups->taskPriorities)) . ']',
            'status'      => 'permit_empty|in_list[' . implode(',', array_keys($lookups->complaintStatuses)) . ']',
        ];
    }

    public function withDetails()
    {
        return $this->select('complaints.*, guests.full_name as guest_name, guests.phone as guest_phone,
                assignee.full_name as assignee_name, reporter.full_name as reporter_name')
            ->join('guests', 'guests.id = complaints.guest_id')
            ->join('users assignee', 'assignee.id = complaints.assigned_to', 'left')
            ->join('users reporter', 'reporter.id = complaints.reported_by', 'left');
    }

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

    /** Open or assigned (not yet resolved) — the dashboard/Guest CRM "open complaints" count. */
    public function countUnresolved(): int
    {
        return $this->whereIn('status', ['open', 'assigned'])->countAllResults();
    }

    public function countForGuest(int $guestId): int
    {
        return $this->where('guest_id', $guestId)->countAllResults();
    }
}
