<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    protected $table = 'cities';
    protected $primaryKey = 'city_id';

    protected $fillable = [
        'city_name',
        'city_id',
        'business_id',
        'description',
        'created_by',
        'ACTIVE',
        'brick_name',
        'brick_id'
    ];

    /**
     * Get the business that owns the city.
     */
    public function business()
    {
        return $this->belongsTo(\App\Business::class);
    }

    /**
     * Get the areas for this city.
     */
    public function areas()
    {
        return $this->hasMany(\App\Area::class, 'city_id', 'city_id');
    }

    /**
     * Get the count of areas for this city.
     */
    public function getAreasCountAttribute($value)
    {
        if ($value === null) {
            // If areas_count is null, calculate it dynamically
            return $this->areas()->count();
        }
        return $value;
    }

    /**
     * Update the areas count for this city.
     */
    public function updateAreasCount()
    {
        $count = $this->areas()->count();
        $this->update(['areas_count' => $count]);
        return $count;
    }

    /**
     * Scope a query to only include cities for a specific business.
     */
    public function scopeForBusiness($query, $business_id)
    {
        return $query->where('business_id', $business_id);
    }

    /**
     * Get cities for dropdown
     */
    public static function forDropdown($business_id)
    {
        $cities = City::forBusiness($business_id)
            ->orderBy('city_name')
            ->pluck('city_name', 'id');

        return $cities;
    }
}
