<?php
// signup.php
require 'db_connect.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(["success" => false, "message" => "Only POST allowed"]);
    exit;
}

// use $_POST form-data
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$contact = isset($_POST['contact']) ? trim($_POST['contact']) : '';

if ($name === '' || $email === '' || $password === '' || $contact === '') {
    echo json_encode(["success" => false, "message" => "All fields are required."]);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(["success" => false, "message" => "Invalid email."]);
    exit;
}

// check duplicate
$email_e = mysqli_real_escape_string($conn, $email);
$check_sql = "SELECT id FROM bilal_users_9f3a WHERE email = '$email_e' LIMIT 1";
$res = mysqli_query($conn, $check_sql);
if ($res && mysqli_num_rows($res) > 0) {
    echo json_encode(["success" => false, "message" => "Email already registered."]);
    exit;
}

// hash password
$hash = password_hash($password, PASSWORD_DEFAULT);
$name_e = mysqli_real_escape_string($conn, $name);
$contact_e = mysqli_real_escape_string($conn, $contact);

$sql = "INSERT INTO bilal_users_9f3a (name, email, password, contact) VALUES ('$name_e', '$email_e', '$hash', '$contact_e')";
if (mysqli_query($conn, $sql)) {
    echo json_encode(["success" => true, "message" => "Registered successfully."]);
} else {
    echo json_encode(["success" => false, "message" => "Registration failed."]);
}
?>
