<?php
 
session_start();

require_once ("connection_sql.php");

 
date_default_timezone_set('Asia/Colombo');  
$created_at = date('Y-m-d H:i:s');  


if (isset($_POST['action']) && $_POST['action'] == "save_location") {  
    
    
    $latitude = $_POST['lat'];
    $longitude = $_POST['lon'];

    
    $company = $_SESSION['company'];
    
    // Prepare SQL query to insert data
    $sql = "INSERT INTO s_locations (latitude, longitude, user_name, created_at) VALUES (:latitude, :longitude, :user_name, :created_at)";
    
    // Prepare the statement
    $stmt = $conn->prepare($sql);
    
    // Bind parameters correctly
    $stmt->bindParam(':latitude', $latitude);
    $stmt->bindParam(':longitude', $longitude);
    $stmt->bindParam(':user_name', $company);  // Corrected parameter name
    $stmt->bindParam(':created_at', $created_at);
    
    // Execute the statement
    if ($stmt->execute()) { 
        $response = array(
            "status" => "success",
            "message" => "Location saved successfully."
        );
    } else { 
        $response = array(
            "status" => "error",
            "message" => "Error saving location."
        );
    }

    // Return JSON response
    echo json_encode($response);

} else {
    // If latitude or longitude is missing, return an error response
    $response = array(
        "status" => "error",
        "message" => "Latitude and longitude are required."
    );
    echo json_encode($response);
}
?>
