<?php
include 'db_conn.php'; 
header('Content-Type: application/json');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = trim($_POST['email']);
    $name = trim($_POST['name']); // nav obligāti
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    // Parbauda paroli
    if ($password !== $confirm_password) {
        echo json_encode(['success' => false, 'error' => 'Paroles nesakrīt!']);
        exit();
    }

    // Parbauda paroles garumu
    if (strlen($password) < 10) {
        echo json_encode(['success' => false, 'error' => 'Parolei jābūt vismaz 10 simbolus garai!']);
        exit();
    }
// Paroļu drošība
if (!preg_match('/[0-9]/', $password) || !preg_match('/[\W]/', $password)) {
    echo json_encode([
        'success' => false,
        'error' => 'Parolei jābūt vismaz vienam ciparam un vienam simbolam!'
    ]);
    exit();
}
// Vai e-pasts nesākas ar simbolu
if (!preg_match('/^[a-zA-Z0-9]/', $email)) {
    echo json_encode([
        'success' => false,
        'error' => 'E-pasts nedrīkst sākties ar simbolu!'
    ]);
    exit();
}
    // Vai e-pasts eksiste
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        echo json_encode(['success' => false, 'error' => 'Šis e-pasts jau tiek izmantots!']);
        exit();
    }

    // Šifrē paroli
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Ievieto datus datubāzē
    $stmt = $conn->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $name, $email, $hashed_password);
    $stmt->execute();

    echo json_encode(['success' => true]);
    exit();
}

echo json_encode(['success' => false, 'error' => 'Nederīgs pieprasījums.']);
$conn->close();
?>
