<?php
$user_id = authenticate();

switch ($method) {
    case 'GET':
        if ($resource_id) {
            // Get commands 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 pending commands for device
            $stmt = $GLOBALS['con']->prepare("
                SELECT * FROM device_commands 
                WHERE device_id = ? AND status = 'pending' 
                ORDER BY created_at ASC
            ");
            $stmt->bind_param("i", $device_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $commands = [];
            while ($row = $result->fetch_assoc()) {
                $commands[] = $row;
            }
            
            echo json_encode($commands);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'Device ID is required']);
        }
        break;
        
    case 'POST':
        // Create new command
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['device_id']) || !isset($data['command_type'])) {
            http_response_code(400);
            echo json_encode(['error' => 'device_id and command_type are required']);
            break;
        }
        
        $device_id = $data['device_id'];
        $command_type = $data['command_type'];
        $command_data = $data['command_data'] ?? null;
        
        // Check permissions
        $stmt = $GLOBALS['con']->prepare("
            SELECT permission_type 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->num_rows === 0) {
            http_response_code(403);
            echo json_encode(['error' => 'No permission to control this device']);
            break;
        }
        
        $permission = $result->fetch_assoc()['permission_type'];
        if ($permission !== 'owner' && $permission !== 'controller') {
            http_response_code(403);
            echo json_encode(['error' => 'Insufficient permissions']);
            break;
        }
        
        // Insert command
        $stmt = $GLOBALS['con']->prepare("
            INSERT INTO device_commands (device_id, user_id, command_type, command_data, status) 
            VALUES (?, ?, ?, ?, 'pending')
        ");
        $command_data_json = $command_data ? json_encode($command_data) : null;
        $stmt->bind_param("iiss", $device_id, $user_id, $command_type, $command_data_json);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'command_id' => $stmt->insert_id]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to create command']);
        }
        break;
        
    case 'PUT':
        // Update command status (for ESP32 devices)
        if (!$resource_id) {
            http_response_code(400);
            echo json_encode(['error' => 'Command ID is required']);
            break;
        }
        
        $command_id = $resource_id;
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['status'])) {
            http_response_code(400);
            echo json_encode(['error' => 'status is required']);
            break;
        }
        
        $status = $data['status'];
        if (!in_array($status, ['executed', 'failed'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid status']);
            break;
        }
        
        $stmt = $GLOBALS['con']->prepare("
            UPDATE device_commands 
            SET status = ?, executed_at = CURRENT_TIMESTAMP 
            WHERE id = ?
        ");
        $stmt->bind_param("si", $status, $command_id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update command']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>
