<?php
require_once '../includes/config.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fullName = $_POST['reg-name'] ?? '';
    $phone = $_POST['reg-phone'] ?? '';
    $email = $_POST['reg-email'] ?? '';
    $password = $_POST['reg-password'] ?? '';

    // Simple server-side validation
    if (empty($fullName) || empty($phone) || empty($email) || empty($password)) {
        echo json_encode(['status' => 'error', 'message' => 'All fields are required.']);
        exit;
    }

    // Check if user already exists
    try {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? OR phone_number = ?");
        $stmt->execute([$email, $phone]);
        if ($stmt->fetch()) {
            echo json_encode(['status' => 'error', 'message' => 'Email or phone number already registered.']);
            exit;
        }

        // Hash password
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

        // Insert user
        $stmt = $pdo->prepare("INSERT INTO users (full_name, phone_number, email, password) VALUES (?, ?, ?, ?)");
        $stmt->execute([$fullName, $phone, $email, $hashedPassword]);

        echo json_encode(['status' => 'success', 'message' => 'Account created successfully!']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
