<?php
session_start();
require_once 'db/config.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $lat = $_POST['lat'];
    $lng = $_POST['lng'];
    $location_label = $_POST['location_label'];
    $location_notes = $_POST['location_notes'];

    if (empty($name) || empty($email) || empty($password)) {
        header("Location: signup.php?error=Please fill all required fields.");
        exit();
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        header("Location: signup.php?error=Invalid email format.");
        exit();
    }

    if (!is_numeric($lat) || !is_numeric($lng)) {
        header("Location: signup.php?error=Invalid location data.");
        exit();
    }

    try {
        $pdo = db();

        $sql = "SELECT id FROM users WHERE email = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            header("Location: signup.php?error=Email already exists.");
            exit();
        }

        $password_hash = password_hash($password, PASSWORD_BCRYPT);

        $sql = "INSERT INTO users (name, email, password, lat, lng, location_label, location_notes) VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        
        if ($stmt->execute([$name, $email, $password_hash, $lat, $lng, $location_label, $location_notes])) {
            $user_id = $pdo->lastInsertId();
            $_SESSION['user_id'] = $user_id;
            $_SESSION['user_name'] = $name;
            header("Location: index.php");
            exit;
        } else {
            die("Error: Could not execute the query.");
        }
    } catch (PDOException $e) {
        die("Could not connect to the database $dbname :" . $e->getMessage());
    }
}
?>