<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

include_once('../../includes/db.php');
header("Content-Type: application/json");

// Collect input
$name     = $_POST['name'] ?? '';
$email    = $_POST['email'] ?? '';
$phone    = $_POST['phone'] ?? '';
$password = $_POST['password'] ?? '';

// ✅ Validate input
if (!$name || !$email || !$phone || !$password) {
    echo json_encode(["status" => false, "message" => "Missing required fields."]);
    exit;
}

$hashed = password_hash($password, PASSWORD_DEFAULT);
$normalizedPhone = str_replace('+973', '', $phone);

// ✅ Check for duplicate email or phone
$exists = fetchOne(
    "SELECT id FROM users WHERE email = ? OR phone = ? OR phone = ?",
    [$email, $phone, $normalizedPhone]
);

if ($exists) {
    echo json_encode(["status" => false, "message" => "❌ Email or phone already registered."]);
    exit;
}

// ✅ Register user
$query = "INSERT INTO users (name, email, phone, password) VALUES (?, ?, ?, ?)";
$success = execute($query, [$name, $email, $phone, $hashed]);

if ($success) {
    echo json_encode(["status" => true, "message" => "✅ User registered successfully."]);
} else {
    echo json_encode(["status" => false, "message" => "❌ Failed to register user."]);
}
?>
