<?php
require_once __DIR__ . '/../../cors.php'; // Enable CORS for React Native
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../middleware/auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonError('Method not allowed', 405);

$body     = getBody();
$name     = trim($body['name']     ?? '');
$email    = strtolower(trim($body['email'] ?? ''));
$phone    = trim($body['phone']    ?? '');
$password = $body['password']      ?? '';

if (!$name || !$email || !$password) jsonError('Name, email and password are required');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) jsonError('Invalid email address');
if (strlen($password) < 6) jsonError('Password must be at least 6 characters');

$db   = getDB();
$stmt = $db->prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?)');
$stmt->execute([$email]);
if ($stmt->fetch()) jsonError('Email already registered', 409);

$id     = generateId();
$hashed = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);

$db->prepare(
    'INSERT INTO users (id, name, email, phone, password, role) VALUES (?, ?, ?, ?, ?, ?)'
)->execute([$id, $name, $email, $phone ?: null, $hashed, 'customer']);

jsonResponse(['message' => 'Account created', 'userId' => $id], 201);
