<?php

namespace App\Http\Controllers\Web\traits;

use App\Models\Region;
use Illuminate\Support\Facades\DB;

trait RegionsDataByUser
{
    public function getLocationsData($user)
    {
        $provinces = null;
        $cities = null;
        $districts = null;

        $countries = Region::select(DB::raw('*, ST_AsText(geo_center) as geo_center'))
            ->where('type', Region::$country)
            ->get();

        if (!empty($user->country_id)) {
            $provinces = Region::getRegionsByTypeAndColumn(Region::$province, 'country_id', $user->country_id);
        }

        if (!empty($user->province_id)) {
            $cities = Region::getRegionsByTypeAndColumn(Region::$city, 'province_id', $user->province_id);
        }

        if (!empty($user->city_id)) {
            $districts = Region::getRegionsByTypeAndColumn(Region::$district, 'city_id', $user->city_id);
        }

        return [
            'countries' => $countries,
            'provinces' => $provinces,
            'cities' => $cities,
            'districts' => $districts,
        ];
    }
}
