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

$email = trim($_POST["email"] ?? '');
$password = $_POST["password"] ?? '';
$password2 = $_POST["password2"] ?? '';
$terms = isset($_POST["terms"]);

if (!$email || !$password || !$password2) {
    echo json_encode(["status" => "error", "type" => "empty"]);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(["status" => "error", "type" => "email"]);
    exit;
}

if ($password !== $password2) {
    echo json_encode(["status" => "error", "type" => "password_mismatch"]);
    exit;
}

if (!$terms) {
    echo json_encode(["status" => "error", "type" => "terms"]);
    exit;
}

$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
// generate 6 digit code
$verification_code = rand(100000, 999999);
$now = date('Y-m-d H:i:s');


try {
    $stmt = $pdo->prepare("INSERT INTO users (email, password, verification_code, code_created_at) VALUES (?, ?, ?, ?)");
    $stmt->execute([$email, $hashedPassword, $verification_code, $now]);

    echo json_encode(["status" => "success"]);

} catch (PDOException $e) {
    if ($e->getCode() == 23000) {
        echo json_encode(["status" => "error", "type" => "exists"]);
    } else {
        echo json_encode(["status" => "error", "type" => "server"]);
    }
}
