<?php

namespace Datacake\Core;
use Datacake\Core\Models\IspCity;

class Utils{
    public $city_cookie = "city";
    /**
     * This function set the cookie for the city
     */
    public function setCity($city_id)
	{
		if (empty($city_id)) {
			return false;
		}
		if (!session_id() && !headers_sent()) {
			session_start();
			if (!empty($city_id)) {
				$_SESSION[$this->city_cookie] = trim($city_id);
				setcookie($this->city_cookie, trim($city_id), time() + (86400 * 60), '/', COOKIE_DOMAIN);
			} else {
				unset($_COOKIE[$this->city_cookie]);
				unset($_SESSION[$this->city_cookie]);
				setcookie($this->city_cookie, null, -1, '/', COOKIE_DOMAIN);
				session_destroy();
				session_write_close();
			}
		}
    }
    /**
     * This function get the Cookie for the city
     */
	public function getCity()
	{   
        $city_id = false;
		if (!empty($_SESSION[$this->city_cookie])) {
			$city_id = $_SESSION[$this->city_cookie];
		} elseif (!empty($_COOKIE[$this->city_cookie])) {
			$city_id = $_COOKIE[$this->city_cookie];
        }
        if($city_id){
            $cityEntity = IspCity::find($city_id);
            if($cityEntity){
                return $cityEntity;
            }
        }
		return false;
	}
}