<?php
session_start();  // Ensure session is started to get logged-in user ID
require '../db.php';
require_once '../envLoader.php';
loadEnv(__DIR__ . '/../../.env');

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

// Check if the user is logged in
if (!isset($_SESSION['userId'])) {
    echo json_encode(['status' => 'error', 'message' => 'User not authenticated.']);
    exit;
}

$userId = $_SESSION['userId'];  // Retrieve user ID from session

// Handle POST Request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect and sanitize form data
    $printerName = filter_input(INPUT_POST, 'printerName', FILTER_SANITIZE_STRING);
    $printerIp = filter_input(INPUT_POST, 'printerIp', FILTER_VALIDATE_IP);
    $serialNumber = filter_input(INPUT_POST, 'serialNumber', FILTER_SANITIZE_STRING);
    $accessCode = filter_input(INPUT_POST, 'accessCode', FILTER_SANITIZE_STRING);

    if (!$printerName || !$printerIp || !$serialNumber || !$accessCode) {
        echo json_encode(['status' => 'error', 'message' => 'All fields are required and IP must be valid.']);
        exit;
    }

    try {
        // Prepare SQL insert statement with user ID
        $stmt = $pdo->prepare("
            INSERT INTO bambuPrinters (printerName, printerIp, mqttPassword, serialNumber, userId)
            VALUES (:printerName, :printerIp, :mqttPassword, :serialNumber, :userId)
        ");
        
        // Execute the query with bound parameters
        $stmt->execute([
            ':printerName' => $printerName,
            ':printerIp' => $printerIp,
            ':mqttPassword' => $accessCode,
            ':serialNumber' => $serialNumber,
            ':userId' => $userId
        ]);

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