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

$db = new Database();

// Check if registrations are allowed
$stmt = $db->query("SELECT setting_value FROM settings WHERE setting_key = 'allow_registrations'");
$allow_registrations = $stmt->fetchColumn();

if ($allow_registrations === 'false') {
    jsonResponse(['success' => false, 'message' => 'New user registrations are currently disabled by the administrator.'], 403);
    exit;
}

$auth = new Auth();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    $email = $input['email'] ?? '';
    $password = $input['password'] ?? '';
    $name = $input['name'] ?? '';
    $role = $input['role'] ?? 'customer';
    $phone = $input['phone'] ?? '';

    try {
        $user_id = $auth->register($email, $password, $name, $role, $phone);
        jsonResponse([
            'success' => true,
            'message' => 'Registration successful!',
            'user_id' => $user_id
        ]);
    } catch (Exception $e) {
        jsonResponse([
            'success' => false,
            'message' => $e->getMessage()
        ], 400);
    }
} else {
    jsonResponse([
        'success' => false,
        'message' => 'Method not allowed'
    ], 405);
}
?>