<?php

class Weather {

    public $weather = array();    // Contains full json decoded weather data from database
    public $coord = array();      // Contains "lat" and "lon"
    public $conditions = array(); // Contains "id", "main", "description", "icon"
    public $stats = array();      // Contains "temp", "feels_like", "temp_min", "temp_max", "pressure", "humidity"
    public $temps = array();      // Contains "current", "min", "max"
    public $sampletime = null;    // Equals DateTime of when weather was sampled
    public $sunrise = null;       // Equals DateTime of Sunrise
    public $sunset = null;        // Equals DateTime of Sunset

    const WEATHERURL = "https://api.openweathermap.org/data/3.0/onecall"
                     . "?lat=" . WEATHERLATTITUDE
                     . "&lon=" . WEATHERLONGITUDE
                     . "&appid=" . WEATHERAPIKEY
                     . "&units=" . WEATHERUNITS;

    public static function deleteOldWeather($days = 10) {
        if ( !is_int($days) ) return false;
        if ( $days < 0 ) return false;
        $query = "DELETE FROM " . AppDB::TABLE_WEATHER . " WHERE DATEDIFF(NOW(), sampledate) > :days";
        $sth = AppDB::getSTH($query);
        if ( $sth === false ) return false;
        $sth->bindValue(":days", $days, PDO::PARAM_INT);
        $sth->execute();
    }

    public static function fetchWeather() {
        $weather = file_get_contents(Weather::WEATHERURL);
        $query = "INSERT INTO " . AppDB::TABLE_WEATHER . " (sampledate, weather) VALUES(NOW(), :weather)";
        $sth = AppDB::getSTH($query);
        if ( $sth === false ) return false;
        $sth->bindValue(":weather", $weather, PDO::PARAM_STR);
        $sth->execute();
    }

    public static function getWeather() {
        $query = "SELECT weather FROM " . AppDB::TABLE_WEATHER . " ORDER BY sampledate DESC LIMIT 1";
        $sth = AppDB::getSTH($query);
        if ( $sth === false ) return false;
        $sth->execute();
        if ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
            return json_decode($row['weather'], true);
        } else {
            return false;
        }
    }

    public function __construct() {
        $weather = self::getWeather();
        $this->weather = $weather;
        $this->coord = array("lat" => $weather["lat"], "lon" => $weather["lon"]);
        $this->conditions = $weather["current"]["weather"][0];
        $this->stats = $weather["current"];
        unset($this->stats["weather"]);
        $this->temps = array("current" => $this->stats["temp"],
                             "min" => $weather["daily"][0]["temp"]["min"],
                             "max" => $weather["daily"][0]["temp"]["max"]
                            );
        $this->sampletime = new DateTime("@".$weather["current"]["dt"], new DateTimeZone('UTC'));
        $this->sampletime->setTimeZone(new DateTimeZone(date_default_timezone_get()));
        $this->sunrise = new DateTime("@".$weather["current"]["sunrise"], new DateTimeZone('UTC'));
        $this->sunrise->setTimeZone(new DateTimeZone(date_default_timezone_get()));
        $this->sunset = new DateTime("@".$weather["current"]["sunset"], new DateTimeZone('UTC'));
        $this->sunset->setTimeZone(new DateTimeZone(date_default_timezone_get()));
    }
}
