<?php
$user_id = authenticate();

switch ($method) {
    case 'GET':
        if ($resource_id) {
            // Get logs for specific device
            $device_id = $resource_id;
            
            // Check permissions
            $stmt = $GLOBALS['con']->prepare("
                SELECT COUNT(*) as count FROM device_permissions 
                WHERE device_id = ? AND user_id = ?
            ");
            $stmt->bind_param("ii", $device_id, $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->fetch_assoc()['count'] == 0) {
                http_response_code(403);
                echo json_encode(['error' => 'No permission to view this device']);
                break;
            }
            
            // Get query parameters
            $limit = $_GET['limit'] ?? 100;
            $log_type = $_GET['type'] ?? null;
            $start_time = $_GET['start_time'] ?? null;
            $end_time = $_GET['end_time'] ?? null;
            
            $where_conditions = ["device_id = ?"];
            $params = [$device_id];
            $types = "i";
            
            if ($log_type) {
                $where_conditions[] = "log_type = ?";
                $params[] = $log_type;
                $types .= "s";
            }
            
            if ($start_time) {
                $where_conditions[] = "timestamp >= ?";
                $params[] = $start_time;
                $types .= "s";
            }
            
            if ($end_time) {
                $where_conditions[] = "timestamp <= ?";
                $params[] = $end_time;
                $types .= "s";
            }
            
            $sql = "
                SELECT * FROM device_logs 
                WHERE " . implode(" AND ", $where_conditions) . "
                ORDER BY timestamp DESC 
                LIMIT ?
            ";
            $params[] = $limit;
            $types .= "i";
            
            $stmt = $GLOBALS['con']->prepare($sql);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $logs = [];
            while ($row = $result->fetch_assoc()) {
                $logs[] = $row;
            }
            
            echo json_encode($logs);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'Device ID is required']);
        }
        break;
        
    case 'POST':
        // Add device log (for ESP32 devices)
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['device_id']) || !isset($data['logs'])) {
            http_response_code(400);
            echo json_encode(['error' => 'device_id and logs are required']);
            break;
        }
        
        $device_id = $data['device_id'];
        $logs = $data['logs'];
        
        // Verify device exists
        $stmt = $GLOBALS['con']->prepare("SELECT id FROM devices WHERE device_id = ?");
        $stmt->bind_param("s", $device_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            http_response_code(404);
            echo json_encode(['error' => 'Device not found']);
            break;
        }
        
        $device_db_id = $result->fetch_assoc()['id'];
        
        // Insert logs
        $success = true;
        $GLOBALS['con']->begin_transaction();
        
        foreach ($logs as $log) {
            if (!isset($log['log_type']) || !isset($log['message'])) {
                $success = false;
                break;
            }
            
            $log_type = $log['log_type'];
            $message = $log['message'];
            
            if (!in_array($log_type, ['info', 'warning', 'error'])) {
                $success = false;
                break;
            }
            
            $stmt = $GLOBALS['con']->prepare("
                INSERT INTO device_logs (device_id, log_type, message) 
                VALUES (?, ?, ?)
            ");
            $stmt->bind_param("iss", $device_db_id, $log_type, $message);
            
            if (!$stmt->execute()) {
                $success = false;
                break;
            }
        }
        
        if ($success) {
            $GLOBALS['con']->commit();
            
            // Update device last_seen
            $stmt = $GLOBALS['con']->prepare("UPDATE devices SET last_seen = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->bind_param("i", $device_db_id);
            $stmt->execute();
            
            echo json_encode(['success' => true]);
        } else {
            $GLOBALS['con']->rollback();
            http_response_code(500);
            echo json_encode(['error' => 'Failed to save logs']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>
