<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

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

switch ($_SERVER['REQUEST_METHOD']) {
    case 'POST':
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['device_id'])) {
            http_response_code(400);
            echo json_encode(['error' => 'device_id is required']);
            break;
        }
        
        $device_id = $data['device_id'];
        $status = $data['status'] ?? 'online';
        $ip_address = $data['ip_address'] ?? $_SERVER['REMOTE_ADDR'];
        $firmware_version = $data['firmware_version'] ?? null;
        $wifi_ssid = $data['wifi_ssid'] ?? null;
        $rssi = $data['rssi'] ?? null;
        
        // Get device database ID
        $stmt = $con->prepare("SELECT id, owner_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 = $result->fetch_assoc();
        $device_db_id = $device['id'];
        $user_id = $device['owner_id'];
        
        // Update device status and last seen
        $stmt = $con->prepare("
            UPDATE devices 
            SET status = ?, last_seen = CURRENT_TIMESTAMP, ip_address = ?, 
                firmware_version = ?
            WHERE id = ?
        ");
        $stmt->bind_param("sssi", $status, $ip_address, $firmware_version, $device_db_id);
        
        if ($stmt->execute()) {
            // Store extra wifi info into a heartbeat event (no wifi_ssid/rssi columns in schema)
            $eventData = json_encode([
                'wifi_ssid' => $wifi_ssid,
                'rssi' => $rssi,
                'firmware_version' => $firmware_version,
                'ip_address' => $ip_address
            ]);
            $ev = $con->prepare("INSERT INTO device_events (device_id, event_type, event_data, source, user_id, status) VALUES (?, 'heartbeat', ?, 'device', ?, 'completed')");
            $ev->bind_param("isi", $device_db_id, $eventData, $user_id);
            $ev->execute();

            // Pending commands via device_events
            $stmt = $con->prepare("
                SELECT id, event_data
                FROM device_events
                WHERE device_id = ? AND event_type = 'command' AND status = 'pending'
                ORDER BY created_at ASC
                LIMIT 5
            ");
            $stmt->bind_param("i", $device_db_id);
            $stmt->execute();
            $result = $stmt->get_result();

            $commands = [];
            while ($row = $result->fetch_assoc()) {
                $payload = $row['event_data'] ? json_decode($row['event_data'], true) : null;
                $commands[] = [
                    'id' => $row['id'],
                    'command_type' => $payload['command_type'] ?? null,
                    'command_data' => $payload['command_data'] ?? null
                ];

                // Mark command as processing
                $update_stmt = $con->prepare("UPDATE device_events SET status = 'processing', processed_at = CURRENT_TIMESTAMP WHERE id = ?");
                $update_stmt->bind_param("i", $row['id']);
                $update_stmt->execute();
            }
            
            echo json_encode([
                'success' => true,
                'message' => 'Heartbeat received',
                'commands' => $commands,
                'timestamp' => date('Y-m-d H:i:s')
            ]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update heartbeat']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>
