<?php

namespace App\Http\Controllers\APIS\AdminApi;

use App\Http\Controllers\Controller;
use App\Services\AdminService;
use Illuminate\Http\Request;
use App\Services\AlarmService;
use Exception;
use PhpParser\Node\Stmt\Return_;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class AlarmController extends Controller
{
    //

    protected $adminService;

    public function __construct(AdminService $adminService)
    {
        $this->adminService = $adminService;
    }


    public function fetchAlarm(Request $request)
    {
        try {
            $severityList = $request->query('severityList', []);
            $startTime = $request->query('startTime', null);
            $endTime = $request->query('endTime', null);

            if (!is_array($severityList)) {
                $severityList = explode(',', $severityList);
            }

            // Debugging: Check received parameters
            Log::info("Fetching alarms with severityList: " . implode(', ', $severityList) .
                      ", startTime: $startTime, endTime: $endTime");

            // Get token for authentication
            $token = $this->adminService->getToken();
            if (!$token) {
                Log::error("Failed to authenticate with ThingsBoard.");
                return response()->json(['error' => 'Authentication failed'], 401);
            }

            // Build API URL with required parameters
            $url = "http://65.0.131.117:8080/api/v2/alarms?pageSize=10&page=0";

            // Append severityList if provided
            if (!empty($severityList)) {
                foreach ($severityList as $severity) {
                    $url .= "&severityList=" . urlencode($severity);
                }
            }

            // Append startTime and endTime if provided
            if (!empty($startTime)) {
                $url .= "&startTime=" . urlencode($startTime);
            }
            if (!empty($endTime)) {
                $url .= "&endTime=" . urlencode($endTime);
            }

            Log::info("Final API URL: " . $url); // Debugging

            // Make API request
            $response = Http::withHeaders([
                'Authorization' => "Bearer $token",
                'Accept'        => 'application/json',
            ])->get($url);

            if (!$response->successful()) {
                Log::error("Failed to fetch ThingsBoard alarms: " . $response->body());
                return response()->json(['error' => 'Failed to fetch alarms'], 500);
            }

            // Return filtered data
            return response()->json(['alarmResponse' => $response->json()['data'] ?? []]);

        } catch (\Exception $e) {
            Log::error("Error fetching ThingsBoard alarms: " . $e->getMessage());
            return response()->json(['error' => 'Server error'], 500);
        }
    }

    public function acknowledgeAlarm(Request $request)
    {
        try {
            // Get alarmId from request
            $alarmId = $request->input('alarmId');


            // Validate alarmId
            if (!$alarmId) {
                return response()->json(['error' => 'alarmId is required'], 400);
            }

            // Debugging: Log received alarm ID
            Log::info("Acknowledging alarm with ID: $alarmId");

            // Get token for authentication
            $token = $this->adminService->getToken();
            if (!$token) {
                Log::error("Failed to authenticate with ThingsBoard.");
                return response()->json(['error' => 'Authentication failed'], 401);
            }

            // Build API URL using alarmId from request
            $url = "http://65.0.131.117:8080/api/v2/alarm/{$alarmId}/ack?alarmId={$alarmId}";

            Log::info("Final API URL: " . $url); // Debugging

            // Make API request
            $response = Http::withHeaders([
                'Authorization' => "Bearer $token",
                'Accept'        => 'application/json',
            ])->post($url);

            if (!$response->successful()) {
                Log::error("Failed to acknowledge ThingsBoard alarm: " . $response->body());
                return response()->json(['error' => 'Failed to acknowledge alarm'], 500);
            }

            // Return success response
            return response()->json([
                'message' => 'Alarm acknowledged successfully',
                'alarmId' => $alarmId
            ]);

        } catch (\Exception $e) {
            Log::error("Error acknowledging ThingsBoard alarm: " . $e->getMessage());
            return response()->json(['error' => 'Server error'], 500);
        }
    }





}