<?php
// Set the header to indicate the response is JSON
header('Content-Type: application/json');

// Include your database connection file.
// Make sure the path is correct relative to the /api/ folder.
require_once '../includes/db.php';

// Prepare a standard response array
$response = array('status' => 'error', 'message' => 'An unknown error occurred.');

// We only accept POST requests for this endpoint
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get data from the app's request
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    // --- Server-Side Validation ---
    if (empty($full_name) || empty($email) || empty($password)) {
        $response['message'] = "All fields are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $response['message'] = "Please enter a valid email address.";
    } elseif (strlen($password) < 8) {
        $response['message'] = "Password must be at least 8 characters long.";
    } else {
        // --- Check if email already exists ---
        $stmt_check = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $stmt_check->bind_param("s", $email);
        $stmt_check->execute();
        $result = $stmt_check->get_result();
        
        if ($result->num_rows > 0) {
            $response['message'] = "An account with this email address already exists.";
        } else {
            // --- If validation passes, create the user ---
            // Securely hash the password
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            
            // Prepare the insert statement
            $stmt_insert = $conn->prepare("INSERT INTO users (full_name, email, password, role) VALUES (?, ?, ?, 'customer')");
            $stmt_insert->bind_param("sss", $full_name, $email, $password_hash);
            
            if ($stmt_insert->execute()) {
                $response['status'] = 'success';
                $response['message'] = "Registration successful! You can now log in.";
            } else {
                $response['message'] = "Database error: Could not create account.";
            }
            $stmt_insert->close();
        }
        $stmt_check->close();
    }
} else {
    $response['message'] = 'Invalid request method. Only POST is accepted.';
}

// Close the database connection
$conn->close();

// Send the final JSON response back to the Sketchware app
echo json_encode($response);
?>
