<?php
session_start();
if (!isset($_SESSION['name'])) {
    http_response_code(401);
    echo json_encode(['message' => 'Unauthorized']);
    die;
}

require_once 'config/db.php';

$data = json_decode(file_get_contents("php://input"));

if (isset($data->cityName) && isset($data->country) && isset($data->flag) && isset($data->date) && isset($data->notes) && isset($data->lat) && isset($data->lng) ) {
    $date = new DateTime($data->date);
    $data->date = $date->format('Y-m-d');
    
    $query = "INSERT INTO items (cityName, country, flag, date, notes, lat, lng) VALUES (:cityName, :country, :flag, :date, :notes, :lat, :lng)";
    $stmt = $pdo->prepare($query);

    $stmt->bindParam(':cityName', $data->cityName);
    $stmt->bindParam(':country', $data->country);
    $stmt->bindParam(':flag', $data->flag);
    $stmt->bindParam(':date', $data->date);
    $stmt->bindParam(':notes', $data->notes);
    $stmt->bindParam(':lat', $data->lat);
    $stmt->bindParam(':lng', $data->lng);
    

    if ($stmt->execute()) {
        $data->id = $pdo->lastInsertId();
        echo json_encode(['message' => 'Item created successfully','id' => $data->id ,'id' => $data->id, 'cityName' => $data->cityName, 'country' => $data->country, 'flag' => $data->flag, 'date' => $data->date, 'notes' => $data->notes, 'lat' => $data->lat, 'lng' => $data->lng ]);
    } else {
        http_response_code(500);
        echo json_encode(['message' => 'Failed to create item']);
        
    }
} else {
    http_response_code(400);
    echo json_encode(['message' => 'Invalid input']);
}
