<?php

namespace App\Models;

class RewarderCityModel extends BaseModel
{
    protected $table = 'rewarder_cities';
    protected $primaryKey = 'id';
    protected $returnType = 'object';
    protected $allowedFields = ['state_id', 'name', 'populercity', 'status', 'created_at', 'updated_at'];

    public function activeWithHierarchy()
    {
        return $this->select('rewarder_cities.*, rewarder_states.name AS state_name, rewarder_countries.name AS country_name')
            ->join('rewarder_states', 'rewarder_states.id = rewarder_cities.state_id', 'left')
            ->join('rewarder_countries', 'rewarder_countries.id = rewarder_states.country_id', 'left')
            ->where('rewarder_cities.status', 1)
            ->orderBy('rewarder_countries.name', 'asc')
            ->orderBy('rewarder_states.name', 'asc')
            ->orderBy('rewarder_cities.name', 'asc')
            ->findAll();
    }

    public function activeOptionList()
    {
        $rows = $this->select('rewarder_cities.id, rewarder_cities.name, rewarder_states.name AS state_name, rewarder_countries.name AS country_name')
            ->join('rewarder_states', 'rewarder_states.id = rewarder_cities.state_id', 'left')
            ->join('rewarder_countries', 'rewarder_countries.id = rewarder_states.country_id', 'left')
            ->where('rewarder_cities.status', 1)
            ->orderBy('rewarder_countries.name', 'asc')
            ->orderBy('rewarder_states.name', 'asc')
            ->orderBy('rewarder_cities.name', 'asc')
            ->findAll();

        return array_map(static function ($r) {
            $parts = array_filter([$r->name ?? '', $r->state_name ?? '', $r->country_name ?? '']);
            return (object) [
                'id' => (int) $r->id,
                'label' => implode(' - ', $parts),
                'city' => (string) ($r->name ?? ''),
                'state' => (string) ($r->state_name ?? ''),
            ];
        }, $rows);
    }
}

