<?php
/**
 * IoT Commands Management API
 * Enhanced with priority queue and cancellation
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, PATCH');
header('Access-Control-Allow-Headers: Content-Type');

require_once '../../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception('Database connection failed');
    }
    
    $method = $_SERVER['REQUEST_METHOD'];
    
    // GET: List commands
    if ($method === 'GET') {
        $device_id = $_GET['device_id'] ?? null;
        $status = $_GET['status'] ?? null;
        $limit = $_GET['limit'] ?? 50;
        
        $query = "SELECT c.*, d.device_name 
                  FROM iot_commands c
                  LEFT JOIN iot_devices d ON c.device_id = d.device_id
                  WHERE 1=1";
        $params = [];
        
        if ($device_id) {
            $query .= " AND c.device_id = ?";
            $params[] = $device_id;
        }
        
        if ($status) {
            $query .= " AND c.status = ?";
            $params[] = $status;
        }
        
        $query .= " ORDER BY c.priority ASC, c.created_at DESC LIMIT ?";
        $params[] = (int)$limit;
        
        $stmt = $db->prepare($query);
        $stmt->execute($params);
        $commands = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($commands as &$command) {
            $command['payload'] = json_decode($command['payload'], true);
        }
        
        echo json_encode(['success' => true, 'commands' => $commands, 'count' => count($commands)]);
    }
    
    // POST: Send new command
    elseif ($method === 'POST') {
        $device_id = $_POST['device_id'] ?? '';
        $action = $_POST['action'] ?? '';
        $payload = $_POST['payload'] ?? null;
        $priority = $_POST['priority'] ?? 5;
        $created_by = $_POST['created_by'] ?? 'admin';
        
        if (empty($device_id) || empty($action)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'device_id and action are required']);
            exit;
        }
        
        // Verify device exists and is active
        $check_device = $db->prepare("SELECT id, is_active FROM iot_devices WHERE device_id = ?");
        $check_device->execute([$device_id]);
        $device = $check_device->fetch();
        
        if (!$device) {
            http_response_code(404);
            echo json_encode(['success' => false, 'error' => 'Device not found']);
            exit;
        }
        
        if (!$device['is_active']) {
            http_response_code(403);
            echo json_encode(['success' => false, 'error' => 'Device is not active']);
            exit;
        }
        
        // Prepare payload
        if ($payload && !is_string($payload)) {
            $payload = json_encode($payload);
        } elseif (!$payload) {
            $payload = null;
        }
        
        $query = "INSERT INTO iot_commands (device_id, action, payload, priority, status, created_by) 
                  VALUES (?, ?, ?, ?, 'pending', ?)";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$device_id, $action, $payload, $priority, $created_by])) {
            $command_id = $db->lastInsertId();
            
            // Log the command
            $log_query = "INSERT INTO iot_logs (device_id, log_type, message, data) 
                         VALUES (?, 'command', ?, ?)";
            $log_data = json_encode(['command_id' => $command_id, 'action' => $action]);
            $db->prepare($log_query)->execute([$device_id, "Command sent: $action", $log_data]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Command sent successfully',
                'command_id' => $command_id
            ]);
        } else {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Failed to send command']);
        }
    }
    
    // PATCH: Cancel command
    elseif ($method === 'PATCH') {
        parse_str(file_get_contents("php://input"), $_PATCH);
        
        $command_id = $_PATCH['command_id'] ?? '';
        $action = $_PATCH['action'] ?? '';
        
        if (empty($command_id)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'command_id is required']);
            exit;
        }
        
        if ($action === 'cancel') {
            $query = "UPDATE iot_commands SET status = 'cancelled' WHERE id = ? AND status = 'pending'";
            $stmt = $db->prepare($query);
            
            if ($stmt->execute([$command_id])) {
                if ($stmt->rowCount() > 0) {
                    echo json_encode(['success' => true, 'message' => 'Command cancelled']);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Command not found or already processed']);
                }
            } else {
                http_response_code(500);
                echo json_encode(['success' => false, 'error' => 'Failed to cancel command']);
            }
        } else {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Invalid action']);
        }
    }
    
    // DELETE: Remove command
    elseif ($method === 'DELETE') {
        parse_str(file_get_contents("php://input"), $_DELETE);
        $command_id = $_DELETE['command_id'] ?? '';
        
        if (empty($command_id)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'command_id is required']);
            exit;
        }
        
        $query = "DELETE FROM iot_commands WHERE id = ?";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$command_id])) {
            echo json_encode(['success' => true, 'message' => 'Command deleted successfully']);
        } else {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Failed to delete command']);
        }
    }
    
    else {
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
