<?php

$projectId = $_POST['projectId'];
$commentId = $_POST['commentId'];
$time      = $_POST['time'];

if ( !$project = $db->row("SELECT * FROM project WHERE id = ?", $projectId) ) {
    http_response_code(403);
    exit;
}

$zip = $project['zip'];

if ( !$weather = $db->row("SELECT * FROM weather WHERE projectId = ? AND time = ?", $project['id'], $time) ) {
    //get lat lon
    $ch = curl_init();
    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);
    

    $lat  = $response->lat;
    $lon  = $response->lon;
    $city = $response->name;

    //get aggregate weather for a timestamp
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.openweathermap.org/data/3.0/onecall/timemachine?lat=$lat&lon=$lon&dt=$time&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);

    $weather = [
        'projectId'     => $project['id'],
        'sheetId'       => $project['sheetId'],
        'temp'          => $response->data[0]->temp,
        // 'precipitation' => $response->data[0]->rain->{3}.'h',
        'description'   => $response->data[0]->weather[0]->description,
        'icon'          => $response->data[0]->weather[0]->icon,
        'city'          => $city,
        'lat'           => $lat,
        'lon'           => $lon,
        'time'          => $time,
        'date'          => date('Y-m-d', $dt),
    ];
    
    $db->insert('weather', $weather);
}

include '../template/daily-log-weather.php';