<?php

namespace App\Models\Control;

use CodeIgniter\Model;

/**
 * Reads/writes rows in the control database's `tenants` table.
 *
 * This is the ONLY model in the app that talks to the control DB — every
 * other model is tenant-scoped (extends App\Models\TenantModel) and never
 * touches this table or this connection.
 */
class TenantRecordModel extends Model
{
    protected $table            = 'tenants';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = [
        'hotel_name',
        'contact_email',
        'contact_phone',
        'slug',
        'db_name',
        'db_user',
        'status',
        'logo_path',
        'primary_color',
        'secondary_color',
    ];

    protected $validationRules = [
        'hotel_name'    => 'required|max_length[150]',
        'contact_email' => 'permit_empty|valid_email|max_length[150]',
        'contact_phone' => 'permit_empty|max_length[20]',
        'slug'          => 'required|alpha_dash|max_length[63]|is_unique[tenants.slug,id,{id}]',
        'db_name'       => 'required|max_length[64]|is_unique[tenants.db_name,id,{id}]',
        'db_user'       => 'permit_empty|max_length[64]',
        'status'        => 'required|in_list[active,suspended]',
    ];

    public function findActiveBySlug(string $slug): ?object
    {
        return $this->where('slug', $slug)->where('status', 'active')->first();
    }

    /**
     * Platform dashboard cards (Hotels, active count, ...) — used by
     * Admin\DashboardController rather than each controller re-querying.
     */
    public function countByStatus(string $status): int
    {
        return $this->where('status', $status)->countAllResults();
    }
}
