<?php
/**
 * ESP8266/ESP32 Control API
 * Enhanced with offline detection and sensor data support
 */

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception('Database connection failed');
    }
    
    // GET: Read pending commands (ESP8266 polls this)
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $device_id = $_GET['device_id'] ?? '';
        $firmware_version = $_GET['firmware_version'] ?? null;
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? null;
        
        if (empty($device_id)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'device_id is required']);
            exit;
        }
        
        // Update device online status, last_seen, IP, and firmware
        // Try to update status column if exists, otherwise just update is_online
        try {
            $update_query = "UPDATE iot_devices 
                            SET is_online = TRUE, 
                                status = 'online',
                                last_seen = NOW(), 
                                ip_address = ?,
                                firmware_version = COALESCE(?, firmware_version)
                            WHERE device_id = ?";
            $update_stmt = $db->prepare($update_query);
            $update_stmt->execute([$ip_address, $firmware_version, $device_id]);
        } catch (PDOException $e) {
            // If status column doesn't exist, update without it
            $update_query = "UPDATE iot_devices 
                            SET is_online = TRUE, 
                                last_seen = NOW(), 
                                ip_address = ?,
                                firmware_version = COALESCE(?, firmware_version)
                            WHERE device_id = ?";
            $update_stmt = $db->prepare($update_query);
            $update_stmt->execute([$ip_address, $firmware_version, $device_id]);
        }
        
        // Get highest priority pending command
        $query = "SELECT * FROM iot_commands 
                  WHERE device_id = ? AND status = 'pending' 
                  ORDER BY priority ASC, created_at ASC 
                  LIMIT 1";
        $stmt = $db->prepare($query);
        $stmt->execute([$device_id]);
        $command = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($command) {
            // Mark command as sent
            $mark_sent = $db->prepare("UPDATE iot_commands SET status = 'sent', sent_at = NOW() WHERE id = ?");
            $mark_sent->execute([$command['id']]);
            
            $payload = $command['payload'] ? json_decode($command['payload'], true) : null;
            
            echo json_encode([
                'success' => true,
                'command_id' => $command['id'],
                'action' => $command['action'],
                'payload' => $payload,
                'priority' => $command['priority']
            ]);
        } else {
            // No pending commands - heartbeat response
            echo json_encode([
                'success' => true,
                'action' => 'none',
                'message' => 'No pending commands'
            ]);
        }
    }
    
    // POST: Update command status or send sensor data
    elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $device_id = $_POST['device_id'] ?? '';
        $command_id = $_POST['command_id'] ?? null;
        $status = $_POST['status'] ?? 'executed';
        $error_message = $_POST['error_message'] ?? null;
        
        // Sensor data (optional)
        $sensor_type = $_POST['sensor_type'] ?? null;
        $sensor_value = $_POST['sensor_value'] ?? null;
        $sensor_unit = $_POST['sensor_unit'] ?? null;
        $sensor_data = $_POST['sensor_data'] ?? null;
        
        if (empty($device_id)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'device_id is required']);
            exit;
        }
        
        // Update device status
        $update_device = $db->prepare("UPDATE iot_devices 
                                       SET is_online = TRUE, last_seen = NOW() 
                                       WHERE device_id = ?");
        $update_device->execute([$device_id]);
        
        // Update command status if command_id provided
        if ($command_id) {
            // Get command details to update pin state
            $cmd_query = "SELECT payload FROM iot_commands WHERE id = ?";
            $cmd_stmt = $db->prepare($cmd_query);
            $cmd_stmt->execute([$command_id]);
            $command = $cmd_stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($command && $command['payload']) {
                $payload = json_decode($command['payload'], true);
                if (isset($payload['gpio']) && isset($payload['state'])) {
                    // Update current_state in device_pins
                    $update_pin = $db->prepare("UPDATE device_pins 
                                               SET current_state = ? 
                                               WHERE device_id = ? AND pin_gpio = ?");
                    $update_pin->execute([$payload['state'], $device_id, $payload['gpio']]);
                }
            }
            
            $update_command = $db->prepare("UPDATE iot_commands 
                                           SET status = ?, executed_at = NOW(), error_message = ? 
                                           WHERE id = ?");
            $update_command->execute([$status, $error_message, $command_id]);
            
            // Log command execution
            $log_msg = $status === 'executed' ? 'Command executed successfully' : 'Command failed';
            $log_query = "INSERT INTO iot_logs (device_id, log_type, message, data) VALUES (?, ?, ?, ?)";
            $log_data = json_encode(['command_id' => $command_id, 'status' => $status, 'error' => $error_message]);
            $db->prepare($log_query)->execute([$device_id, $status === 'executed' ? 'info' : 'error', $log_msg, $log_data]);
        }
        
        // Store sensor data if provided
        if ($sensor_type && $sensor_value !== null) {
            $sensor_query = "INSERT INTO iot_sensors_data (device_id, sensor_type, value, unit, raw_data) 
                            VALUES (?, ?, ?, ?, ?)";
            $db->prepare($sensor_query)->execute([
                $device_id, 
                $sensor_type, 
                $sensor_value, 
                $sensor_unit,
                $sensor_data
            ]);
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Status updated successfully'
        ]);
    }
    
    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()
    ]);
}
?>
