<?php
session_start();
require '../db.php';
header('Content-Type: application/json');

if (!isset($_SESSION['userId'])) {
    echo json_encode(['status' => 'error', 'message' => 'User not authenticated.']);
    exit;
}

$userId = $_SESSION['userId'];

try {
    // Subquery to fetch latest telemetry for each printer
    $stmt = $pdo->prepare("
        SELECT p.*, t.telemetry, t.recordedAt
        FROM bambuPrinters p
        LEFT JOIN printerTelemetry t
        ON t.id = (
            SELECT id FROM printerTelemetry 
            WHERE printerId = p.id 
            ORDER BY recordedAt DESC 
            LIMIT 1
        )
        WHERE p.userId = :userId
    ");
    
    $stmt->execute([':userId' => $userId]);
    $printers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $result = [];
    foreach ($printers as $printer) {
        $telemetry = json_decode($printer['telemetry'], true);

        $bedTemp = isset($telemetry['print']['bed_temper']) ? $telemetry['print']['bed_temper'] : 'N/A';
        $nozzleTemp = isset($telemetry['print']['device']['nozzle']['0']['temp']) 
                      ? $telemetry['print']['device']['nozzle']['0']['temp'] 
                      : 'N/A';
        $jobName = isset($telemetry['subtask_name']) ? $telemetry['subtask_name'] : 'No job running';
        $status = isset($telemetry['print']['gcode_state']) ? $telemetry['print']['gcode_state'] : 'Unknown';
        
        // AMS Data
        $humidity = isset($telemetry['print']['ams']['ams'][0]['humidity']) 
                    ? $telemetry['print']['ams']['ams'][0]['humidity'] 
                    : 0;
        $trays = isset($telemetry['print']['ams']['ams'][0]['tray']) 
                 ? $telemetry['print']['ams']['ams'][0]['tray'] 
                 : [];

        // Structure tray data for direct output
        $trayData = [];
        foreach ($trays as $tray) {
            $trayData[] = [
                'id' => $tray['id'],
                'color' => isset($tray['tray_color']) ? $tray['tray_color'] : 'ccc'
            ];
        }

        $result[] = [
            'printerId' => $printer['id'],
            'printerName' => $printer['printerName'],
            'serialNumber' => $printer['serialNumber'],
            'printerIp' => $printer['printerIp'],
            'bedTemp' => $bedTemp,
            'nozzleTemp' => $nozzleTemp,
            'jobName' => $jobName,
            'status' => $status,
            'humidity' => $humidity,
            'trays' => $trayData,
            'recordedAt' => $printer['recordedAt'] ?? 'Never'
        ];
    }

    echo json_encode(['status' => 'success', 'data' => $result]);

} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Failed to fetch printers: ' . $e->getMessage()]);
}
?>
