<?php
$must_cache = false;
$weather_cy_err = array();
$optres ['css'][] = $module_css_path . "amodules/cyprus_weather/css/cyprus_weather.css";
$optres ['js'][] = $path . "amodules/cyprus_weather/js/cyprus_weather.v2.js";
?>
    <p>
        <strong>Temperature in: </strong>
        <a href="#" class="t-conv" data-conv="c">Centigrade (&deg; C)</a> /
        <a href="#" class="t-conv" data-conv="f">Fahrenheit  (&deg; F)</a>
    </p>
    <br>
<?php

//$currentXML = @file_get_contents($path.'weather/current.xml');
//$fivedayXML = @file_get_contents($path.'weather/fiveday.xml');

function convert_temp($temp, $to_scale="F", $from_scale="C"){
    if($from_scale == "C" && $to_scale == "F") {
        $conv = $temp * 1.8 + 32;
        if(is_float($conv)) {
            $ret = number_format($conv, 1, '.','');
        }
        else {
            $ret = number_format($conv, 0, '.','');
        }
    }

    if($from_scale == "F" && $to_scale == "C") {
        $conv = ($temp - 32) * 0.18;
        if(is_float($conv)) {
            $ret = number_format($conv, 1, '.','');
        }
        else {
            $ret = number_format($conv, 0, '.','');
        }
    }

    if($from_scale == $to_scale) $ret = $temp;

    return $ret;
}

$currentXML = dirname(__FILE__) . '/../../acrons/weather/current.xml';
$fivedayXML = dirname(__FILE__) . '/../../acrons/weather/fiveday.xml';

$weather_cy_file = dirname(__FILE__) . '/../../acrons/weather/weather_cy.html';
$weather_cy_retake = false;
$weather_cy_have_old = false;

if(!file_exists($weather_cy_file)) {
    $weather_cy_retake = true;
}
else {
    $weather_cy_have_old = true;
    if(time() - filemtime($weather_cy_file) > 3600*2) {
        $weather_cy_retake = true;
    }
}

$weather_cy_retake = true;

if($weather_cy_retake) {
    ob_start();

    $towns = array('Nicosia','Limassol','Larnaca','Paphos','Famagusta');
    $towns_acc = array('ID120', 'ID119', 'ID118', 'ID121', 'ID117');

    try {
        /**************** ADELIN *********************************************************************/
        libxml_use_internal_errors(true);
        if (file_exists($currentXML) && file_exists($fivedayXML)) {
            $current_w = array();

            $xml = new \XMLReader();
            $xml->open($currentXML);

            while (@$xml->read()) {  }; // empty loop

            if (count(libxml_get_errors ())==0) {
                //echo "provided xml is well formed and xsd-valid";
                //now you can start processing without @ as document was validated against xsd and is xml-wellformed
            }
            else {
                //echo "provided xml is wrong and/or not xsd-valid. stopping";
                $weather_cy_err [] = "XML file " . $currentXML . " is malformed";
            }
            $xml->close();

            // Parsing a the current weather document with Expand and SimpleXML
            $reader = new XMLReader();
            if (count($weather_cy_err) == 0 && $reader->XML(file_get_contents($currentXML))) {
                $import_date = time();
                while ($reader->read()) {
                    switch ($reader->nodeType) {
                        case (XMLREADER::ELEMENT):
                            if ($reader->localName == "current") {
                                $node = $reader->expand();
                                $dom = new DomDocument();
                                $n = $dom->importNode($node, true);
                                $dom->appendChild($n);
                                $sxe = simplexml_import_dom($n);
                                $location = strval($sxe->location);

                                if (in_array($location, $towns_acc)) {
                                    if (!isset($current_w["$location"])) {
                                        $current_w["$location"] = array();
                                    }


                                    $current_w["$location"]['phrase'] = strval($sxe->phrase);
                                    $current_w["$location"]['temp'] = strval($sxe->temp);

                                    if ($sxe->temp->attributes() != null) {
                                        $temp_attributes = $sxe->temp->attributes();
                                        $temp_units = strval($temp_attributes->units);
                                    } else {
                                        $temp_units = "C";
                                    }
                                    $current_w["$location"]['temp_units'] = $temp_units;


                                    if ($sxe->aptemp->attributes() != null) {
                                        $aptemp_attributes = $sxe->aptemp->attributes();
                                        $aptemp_unit = strval($aptemp_attributes->unit);
                                    } else {
                                        $aptemp_unit = "C";
                                    }
                                    $current_w["$location"]['aptemp'] = strval($sxe->aptemp);
                                    $current_w["$location"]['aptemp_unit'] = $aptemp_unit;

                                    if ($sxe->wndchl->attributes() != null) {
                                        $wndchl_attributes = $sxe->wndchl->attributes();
                                        $wndchl_unit = strval($wndchl_attributes->unit);
                                    } else {
                                        $wndchl_unit = "C";
                                    }
                                    $current_w["$location"]['wndchl'] = strval($sxe->wndchl);
                                    $current_w["$location"]['wndchl_unit'] = $wndchl_unit;

                                    if ($sxe->rhumid->attributes() != null) {
                                        $rhumid_attributes = $sxe->rhumid->attributes();
                                        $rhumid_unit = strval($rhumid_attributes->unit);
                                    } else {
                                        $rhumid_unit = "%";
                                    }
                                    $current_w["$location"]['rhumid'] = strval($sxe->rhumid);
                                    $current_w["$location"]['rhumid_unit'] = $rhumid_unit;

                                    $current_w["$location"]['wind_dir'] = strval($sxe->wind_dir);

                                    if ($sxe->windspeed->attributes() != null) {
                                        $windspeed_attributes = $sxe->windspeed->attributes();
                                        $windspeed_unit = strval($windspeed_attributes->unit);
                                    } else {
                                        $windspeed_unit = "kph";
                                    }
                                    $current_w["$location"]['windspeed'] = strval($sxe->windspeed);
                                    $current_w["$location"]['windspeed_unit'] = $windspeed_unit;

                                    if ($sxe->pres->attributes() != null) {
                                        $press_attributes = $sxe->pres->attributes();
                                        $pres_unit = strval($press_attributes->unit);
                                    } else {
                                        $pres_unit = "kpa";
                                    }
                                    $current_w["$location"]['pres'] = strval($sxe->pres);
                                    $current_w["$location"]['pres_unit'] = $pres_unit;

                                    if ($sxe->vis->attributes() != null) {
                                        $vis_attributes = $sxe->vis->attributes();
                                        $vis_unit = strval($vis_attributes->unit);
                                    } else {
                                        $vis_unit = "km";
                                    }
                                    $current_w["$location"]['vis'] = strval($sxe->vis);
                                    $current_w["$location"]['vis_unit'] = $vis_unit;

                                    $current_w["$location"]['icon'] = strval($sxe->icon);

                                }


                            }
                    }
                }
            } else {
                $msg .= "Cannot open for read $currentXML" . "\n";
            }


            $xml = new \XMLReader();
            $xml->open($fivedayXML);

            while (@$xml->read()) {  }; // empty loop

            if (count(libxml_get_errors ())==0) {
                //echo "provided xml is well formed and xsd-valid";
                //now you can start processing without @ as document was validated against xsd and is xml-wellformed
            }
            else {
                //echo "provided xml is wrong and/or not xsd-valid. stopping";
                $weather_cy_err [] = "XML file " . $fivedayXML . " is malformed";
            }
            $xml->close();

            $reader = new XMLReader();
            if ((count($weather_cy_err) == 0) && $reader->open("$fivedayXML")) {
                $import_date = time();
                while ($reader->read()) {
                    switch ($reader->nodeType) {
                        case (XMLREADER::ELEMENT):
                            if ($reader->localName == "forecast") {
                                $node = $reader->expand();
                                $dom = new DomDocument();
                                $n = $dom->importNode($node, true);
                                $dom->appendChild($n);
                                $sxe = simplexml_import_dom($n);
                                $citycode = "";
                                $get_for_city = false;
                                $kk = 0;
                                foreach ($sxe->children() as $item) {
                                    //var_dump($item);
                                    if ($item->getName() == "location") {
                                        $citycode = strval($sxe->location);

                                        if (in_array($citycode, $towns_acc)) {
                                            if (!isset($current_w["$citycode"])) {
                                                $current_w["$citycode"] = array();
                                            }
                                            $get_for_city = true;
                                            $current_w["$citycode"]['fivedays'] = array();
                                            $kk = -1;
                                        }
                                    } elseif ($item->getName() == "citycode") {
                                        $citycode = strval($sxe->citycode);

                                        if (in_array($citycode, $towns_acc)) {
                                            if (!isset($current_w["$citycode"])) {
                                                $current_w["$citycode"] = array();
                                            }
                                            $get_for_city = true;
                                            $current_w["$citycode"]['fivedays'] = array();
                                            $kk = -1;
                                        }
                                    } elseif ($item->getName() == "day") {
                                        $name = "";
                                        $icon = "";
                                        $high = "";
                                        $high_unit = "";
                                        $low = "";
                                        $low_unit = "";
                                        $phrase = "";
                                        if ($get_for_city) {

                                            foreach ($item->children() as $dd) {
                                                if ($dd->getName() == "name") {
                                                    $current_w["$citycode"]['fivedays'][$kk]['name'] = strval($item->name);
                                                }
                                                if ($dd->getName() == "icon") {
                                                    $current_w["$citycode"]['fivedays'][$kk]['icon'] = strval($item->icon);
                                                }
                                                if ($dd->getName() == "high") {
                                                    if ($dd->attributes() != "") {
                                                        $high_attributes = $dd->attributes();
                                                        $high_unit = strval($high_attributes->unit);
                                                    } else {
                                                        $high_unit = "C";
                                                    }
                                                    $current_w["$citycode"]['fivedays'][$kk]['high'] = strval($item->high);
                                                    $current_w["$citycode"]['fivedays'][$kk]['high_unit'] = $high_unit;
                                                }
                                                if ($dd->getName() == "low") {
                                                    if ($dd->attributes() != "") {
                                                        $low_attributes = $dd->attributes();
                                                        $low_unit = strval($low_attributes->unit);
                                                    } else {
                                                        $low_unit = "C";
                                                    }
                                                    $current_w["$citycode"]['fivedays'][$kk]['low'] = strval($item->low);
                                                    $current_w["$citycode"]['fivedays'][$kk]['low_unit'] = $low_unit;
                                                }
                                                if ($dd->getName() == "phrase") {
                                                    $current_w["$citycode"]['fivedays'][$kk]['phrase'] = strval($item->phrase);
                                                }

                                            }
                                        }
                                    }
                                    $kk++;
                                }
                            }
                    }
                }
            } else {
                $msg .= "Cannot open for read $fivedayXML" . "\n";
            }

            //echo "<pre>";
            //print_r($current_w);
            //echo "</pre>";

            $CorF = 'C';

            if (isset($_GET['displaytemp']) && $_GET['displaytemp'] == 'f') {

                foreach ($current_w as $city => $current) {
                    $current['temp'] = round($current['temp'] * (9 / 5) + 32);
                    $current['wndchl'] = round($current['wndchl'] * (9 / 5) + 32);

                    for ($j = 0; $j < 5; $j++) {
                        $current['fivedays'][$j]['high'] = round($current['fivedays'][$j]['high'] * (9 / 5) + 32);
                        $current['fivedays'][$j]['low'] = round($current['fivedays'][$j]['low'] * (9 / 5) + 32);
                    }
                }
                $CorF = 'F';
            }

            $faren = array();
            foreach ($current_w as $city => $current) {
                $faren['temp'] = round($current['temp'] * (9 / 5) + 32);
                $faren['wndchl'] = round($current['wndchl'] * (9 / 5) + 32);

                for ($j = 0; $j < 5; $j++) {
                    $faren['fivedays'][$j]['high'] = round($current['fivedays'][$j]['high'] * (9 / 5) + 32);
                    $faren['fivedays'][$j]['low'] = round($current['fivedays'][$j]['low'] * (9 / 5) + 32);
                }
            }

            ?>
            <style>


            </style>
            <?php

            foreach ($towns_acc as $i => $town_code) {
                $current = $current_w[$town_code];

                //echo '<pre>$current = ', var_export($current, true), '</pre>';

                ?>

                <section class="box box-compact box-weather">
                    <header class="box-header">
                        <i class="fa fa-cloud text-primary"></i> <h2><?=$towns[$i];?> Weather</h2>
                    </header>
                    <div class="box-body no-padding">
                        <div class="row no-margin">
                            <div class="col-sm-4">
                                <div class="row">
                                    <div class="col-xs-5 w-rborder text-center">
                                        <table class="w-main">
                                            <thead>
                                            <tr>
                                                <th class="text-center">
                                                    <span class="w-current">CURRENT</span>
                                                </th>
                                            </tr>
                                            </thead>
                                            <tbody>
                                            <tr>
                                                <td class="text-center w-vcenter">
                                                    <span class="w-temp w-tconv"
                                                          data-c="<?= $current['temp']; ?>&deg;C"
                                                          data-f="<?= convert_temp($current['temp'], 'F'); ?>&deg;F"
                                                        ><?= $current['temp']; ?>&deg;C</span>
                                                </td>
                                            </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="col-xs-5 w-rborder text-center">
                                        <table class="w-main">
                                            <thead>
                                            <tr>
                                                <th class="text-center">
                                                    <span class="w-current"><?= $current['phrase']; ?></span>

                                                </th>
                                            </tr>
                                            </thead>
                                            <tbody>
                                            <tr>
                                                <td class="text-center w-vcenter">
                                                    <img src="<?= $path; ?>images/icons/weather_icons/current/<?= $current['icon']; ?>.png" width="80" height="50">
                                                </td>
                                            </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="row">
                                    <div class="col-xs-5 w-tborder text-center">
                                        <table class="w-specs">
                                            <tr>
                                                <th role="rowheader">Visibility:</th>
                                                <td class="text-right"><?= $current['vis']; ?> km</td>
                                            </tr>
                                            <tr>
                                                <th role="rowheader">Pressure:</th>
                                                <td class="text-right">
                                                    <?php
                                                    if ($current['pres'] != '') {
                                                        echo $current['pres'] . " " . $current['pres_unit'];
                                                    }
                                                    else {
                                                        echo "N/A";
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <th role="rowheader">Humidity:</th>
                                                <td class="text-right"><?php echo $current['rhumid']; ?>%</td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div class="col-xs-5 w-tborder text-center">
                                        <table class="w-specs">
                                            <tr>
                                                <th role="rowheader">Wind speed:</th>
                                                <td class="text-right"><?php echo $current['windspeed'] . " " . $current['windspeed_unit']; ?></td>
                                            </tr>
                                            <tr>
                                                <th role="rowheader">Wind direction:</th>
                                                <td class="text-right"><?= $current['wind_dir']; ?></td>
                                            </tr>
                                            <tr>
                                                <th role="rowheader">Wind Chill:</th>
                                                <td class="text-right w-tconv"
                                                    data-c="<?= $current['wndchl']; ?>&deg;C"
                                                    data-f="<?= convert_temp($current['wndchl'], 'F'); ?>&deg;F"
                                                    ><?= $current['wndchl']; ?> &deg;C</td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row no-padding no-margin">
                            <?php
                            foreach($current['fivedays'] as $di=>$ddata) {
                                ?>
                                <div class="w-dbox w-rborder col-sm-2 text-center no-padding">
                                    <span class="w-dname"><?= $ddata['name']; ?></span>
                                    <span class="w-dicon">
                                        <img class="img-responsive center-block"
                                             src="<?= $path; ?>images/icons/weather_icons/current/<?= $current['fivedays'][$di]['icon']; ?>.png"
                                             width="80" height="50" alt="<?= $current['fivedays'][$di]['phrase']; ?>">
                                    </span>
                                    <table class="w-dspecs">
                                        <tr>
                                            <th role="rowheader">High</th>
                                            <td class="text-right w-tconv"
                                                data-c="<?= $current['fivedays'][$di]['high']; ?>&deg;C"
                                                data-f="<?= convert_temp($current['fivedays'][$di]['high'], 'F'); ?>&deg;F"
                                                >
                                                <?= $current['fivedays'][$di]['high']; ?>&deg;C
                                            </td>
                                        </tr>
                                        <tr>
                                            <th role="rowheader">Low</th>
                                            <td class="text-right w-tconv"
                                                data-c="<?= $current['fivedays'][$di]['low']; ?>&deg;C"
                                                data-f="<?= convert_temp($current['fivedays'][$di]['low'], 'F'); ?>&deg;F"
                                                >
                                                <?= $current['fivedays'][$di]['low']; ?>&deg;C
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                                <?php
                            }
                            ?>
                        </div>

                    </div>
                </section>
                <br/>
                <?php
            }

        }
    }
    catch(Exception $e) {
        $weather_cy_err [] = $e->getMessage();

    }

    $weather_cy = ob_get_contents();
    ob_end_clean();

    if(count($weather_cy_err) > 0) {
        if($weather_cy_have_old) {

            echo(file_get_contents($weather_cy_file, false, stream_context_create([
                "ssl" => [
                    "verify_peer"=>false,
                    "verify_peer_name"=>false,
                ]
            ])));
        }
        else {
            echo '<p><b>Please revisit in a few minutes as we are currently updating our weather data.</b></p>';
        }
    }
    else {
        file_put_contents($weather_cy_file, $weather_cy);
        echo $weather_cy;
    }
}
else {
    echo file_get_contents($weather_cy_file, false, [
        "ssl" => [
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        ]
    ]);
}


if(count($weather_cy_err) > 0) {

    mail("adelin.feraru@gmail.com","weaderD.php Weather Problem", var_export($weather_cy_err, true));
    //echo '<pre>', var_export($weather_cy_err, true), '</pre>';
}
/*******************END***********************************************************************/
