<?php
include 'inc/db.php';
date_default_timezone_set('America/New_York');

if($_SERVER['REQUEST_METHOD'] == 'POST'){

    $name  = trim($_POST['name']);
    $email = trim($_POST['email']);
    $pass  = trim($_POST['password']);
    $role  = $_POST['role'] ?? 'user';
    $password = md5($pass);
    $date     = date('Y-m-d H:i:s');

    // Check empty fields (extra backend validation)
    if(empty($name) || empty($email) || empty($pass)){
        echo "All fields are required";
        exit;
    }

    // Check email uniqueness
    $chk = mysqli_query($conn, "SELECT id FROM tbl_register WHERE email='$email'");
    if (mysqli_num_rows($chk) > 0) {
        echo "Email already exists";
        exit;
    }

    // Insert user
    $sql = "INSERT INTO tbl_register 
            (`name`, `email`, `password`, `role`, `created_date`) 
            VALUES 
            ('$name', '$email', '$password', '$role', '$date')";

    if (mysqli_query($conn, $sql)) {
        echo 1; // success
    } else {
        echo "Database error: ".mysqli_error($conn);
    }
}
?>
