<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Area extends Model
{
    protected $table = 'areas';

    protected $fillable = [
        'brick_id',
        'brick_name',
        'city_id',
        'status',
        'business_id'
    ];

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        // When an area is created, increment the city's areas count
        static::created(function ($area) {
            if ($area->city) {
                $area->city->updateAreasCount();
            }
        });

        // When an area is deleted, decrement the city's areas count
        static::deleted(function ($area) {
            if ($area->city) {
                $area->city->updateAreasCount();
            }
        });

        // When an area is updated (e.g., status change), update the city's areas count
        static::updated(function ($area) {
            if ($area->city) {
                $area->city->updateAreasCount();
            }
        });
    }

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

    /**
     * Get the city that owns the area.
     */
    public function city()
    {
        return $this->belongsTo(\App\City::class, 'city_id', 'city_id');
    }

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

    /**
     * Scope a query to only include active areas.
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Get areas for dropdown
     */
    public static function forDropdown($business_id, $city_id = null)
    {
        $query = Area::forBusiness($business_id)->active();
        
        if ($city_id) {
            $query->where('city_id', $city_id);
        }
        
        $areas = $query->orderBy('brick_name')
            ->pluck('brick_name', 'id');

        return $areas;
    }
}
