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

$auth = new Auth();
$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;
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $name = $input['name'] ?? '';
    $email = $input['email'] ?? '';
    $password = $input['password'] ?? '';
    $role = $input['role'] ?? 'customer';
    $phone = $input['phone'] ?? '';
    
    // Validation
    if (empty($name) || empty($email) || empty($password) || empty($role)) {
        jsonResponse([
            'success' => false,
            'message' => 'All fields are required'
        ], 400);
    }
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        jsonResponse([
            'success' => false,
            'message' => 'Invalid email format'
        ], 400);
    }
    
    try {
        $userId = $auth->register($email, $password, $name, $role, $phone);
        jsonResponse([
            'success' => true,
            'message' => 'Registration successful',
            'user_id' => $userId
        ]);
    } catch (Exception $e) {
        jsonResponse([
            'success' => false,
            'message' => $e->getMessage()
        ], 400);
    }
} else {
    jsonResponse([
        'success' => false,
        'message' => 'Method not allowed'
    ], 405);
}
?>