<?php
// register_process.php - Handles admin registration form submission

// Include the database configuration file
// IMPORTANT: Ensure 'config.php' is in the same directory as this file.
require_once 'config.php';

// Set header to return JSON response
// This tells the browser that the response will be a JSON object
header('Content-Type: application/json');

// Check if the request method is POST
// This script should only be accessed via a POST request from the registration form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the raw POST data from the request body
    // This is how PHP reads JSON data sent from a JavaScript fetch API call
    $input = file_get_contents('php://input');
    $data = json_decode($input, true); // Decode the JSON string into an associative PHP array

    // Validate and sanitize input data
    // filter_var() is used to clean the input and prevent security vulnerabilities like XSS.
    // ?? '' is a null coalescing operator, ensuring a default empty string if the key doesn't exist.
    $fullName = filter_var($data['fullName'] ?? '', FILTER_SANITIZE_STRING);
    $username = filter_var($data['username'] ?? '', FILTER_SANITIZE_STRING);
    $email = filter_var($data['email'] ?? '', FILTER_SANITIZE_EMAIL);
    $password = $data['password'] ?? ''; // Password will be hashed, so we don't sanitize it as a string yet
    $userType = $data['userType'] ?? ''; // Password will be hashed, so we don't sanitize it as a string yet

    // Basic server-side validation
    // Check if any required fields are empty
    if (empty($fullName) || empty($username) || empty($email) || empty($password)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required.']);
        exit; // Stop script execution
    }

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => 'Invalid email format.']);
        exit; // Stop script execution
    }

    // Hash the password before storing it in the database
    // password_hash() is the recommended and secure way to store passwords.
    // PASSWORD_DEFAULT uses the strongest available hashing algorithm.
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);

    // Prepare an INSERT SQL statement to add the new admin to the 'admins' table
    // Using prepared statements with PDO is CRITICAL for preventing SQL injection attacks.
    // ':placeholder' syntax is used for parameters.
    $sql = "INSERT INTO admins (full_name, username, email, password_hash, is_super_admin) VALUES (:full_name, :username, :email, :password_hash, :is_super_admin)";

    try {
        // Prepare the statement using the PDO connection object ($pdo from config.php)
        $stmt = $pdo->prepare($sql);

        // Bind parameters to the prepared statement
        // This links the PHP variables to the SQL placeholders securely.
        $stmt->bindParam(':full_name', $fullName);
        $stmt->bindParam(':username', $username);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':password_hash', $passwordHash);
        $stmt->bindParam(':is_super_admin', $userType);

        // Execute the prepared statement
        if ($stmt->execute()) {
            // If execution is successful, send a success JSON response
            echo json_encode(['success' => true, 'message' => 'Registration successful! You can now log in.']);
        } else {
            // If execution fails for other reasons, send a generic failure message
            echo json_encode(['success' => false, 'message' => 'Registration failed. Please try again.']);
        }
    } catch (PDOException $e) {
        // Catch any PDO (database) exceptions
        // Check for specific error codes like 23000 (integrity constraint violation)
        // This typically means a duplicate unique value (username or email in this case)
        if ($e->getCode() == 23000) {
            echo json_encode(['success' => false, 'message' => 'Username or Email already exists.']);
        } else {
            // For other database errors, provide a more detailed message (good for debugging, but be careful in production)
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
    }
} else {
    // If the request method is not POST (e.g., someone tries to access it directly via GET)
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
?>
