<?php
    $zip  = urlencode($_POST['zip']);
    $view = $_POST['view'];
// echo $city."<br>";
    $ch = curl_init();
    // curl_setopt($ch, CURLOPT_URL, "http://api.openweathermap.org/geo/1.0/direct?q=$city,tn,us&limit=1&appid=6ac59cfe89efa30a2359dd9462cdaf61");
    curl_setopt($ch, CURLOPT_URL, "http://api.openweathermap.org/geo/1.0/zip?zip=$zip,US&limit=1&appid=".OWM_API_TOKEN);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json, Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = json_decode(curl_exec($ch));
    curl_close($ch);

    // echo "<pre>";
    // var_dump($response);
    // echo "</pre>";

    // $lat = ( $response[0]->lat )
    //     ? $response[0]->lat
    //     : $response->lat;
    // ;
    // $lon = ( $response[0]->lon )
    //     ? $response[0]->lon
    //     : $response->lon;
    // ;
    $lat = $response->lat;
    $lon = $response->lon;
    // echo $lat."/".$lon;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.openweathermap.org/data/3.0/onecall?lat=$lat&lon=$lon&exclude=alerts&units=imperial&appid=".OWM_API_TOKEN);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json, Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = json_decode(curl_exec($ch));
    curl_close($ch);

    // echo "<pre>";
    // var_dump($response);
    // echo "</pre>";

    $days  = $response->daily;
    $hours = $response->hourly;

    $allowed = ( $user['admin'] )
        ? 1
        : $db->cell("SELECT social FROM client WHERE userId = ?", $user['id'])
    ;
    if ( $view == 's' && $allowed ) {
        include '../template/forecast-social.php';  
    } else {
        include '../template/forecast.php';
    }
?>
