<?php

namespace App\Http\Controllers\APIS\AdminApi;

use App\Http\Controllers\Controller;
use App\Models\Asset;
use App\Models\Customer;
use App\Models\Device;
use App\Services\AdminService;
use App\Services\CustomerInfoService;
use Illuminate\Container\Attributes\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Models\UserAssetLink;

class AdminDashboardController extends Controller
{
    protected $adminService;

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



    public function adminDashboard()
{
    try {
        $token = $this->adminService->getToken();
        $totalCustomers = Customer::count();
        $totalAssets = Asset::count();
        // $totalDevices = Device::count();
        $deviceIds = Device::where(['active' => 1])->get()
        ->pluck('id')
        ->flatten()
        ->toArray();



        $customers = Customer::select('name', 'country', 'state', 'city')->get();

        $activeDevices = 0;
        $inactiveDevices = 0;
        $activeAlarmsCount = 0;
        $warningAlarmsCount = 0;
        $criticalAlarmsCount = 0;

        if ($token) {
            $baseUrl = env('THINGSBOARD_URL');

            $totalDevices = $this->customerInfoService->getDevicesCount($deviceIds);
            $alarmsResponse = $this->customerInfoService->fetchDeviceAlarms($deviceIds);

            // $alarmsResponse = Http::withHeaders([
            //     'Authorization' => "Bearer $token",
            //     'Accept' => 'application/json',
            // ])->get("{$baseUrl}api/v2/alarms", [
            //     'pageSize' => 1000,
            //     'page' => 0,
            //     'status' => 'ACTIVE'
            // ]);

            // if ($alarmsResponse->successful()) {
                // $alarmsData = $alarmsResponse->json();

                $activeAlarmsCount = $alarmsResponse['count'] ?? 0;

                if (isset($alarmsResponse['data'])) {
                    foreach ($alarmsResponse['data'] as $alarm) {
                        $severity = strtoupper($alarm['severity'] ?? '');
                        if ($severity === 'CRITICAL') {
                            $criticalAlarmsCount++;
                        } elseif ($severity === 'WARNING') {
                            $warningAlarmsCount++;
                        }
                    }
                }
            // }
        }

        return response()->json([
            'success' => true,
            'total_customers' => $totalCustomers,
            'total_assets' => $totalAssets,
            'devices' => [
                'total_devices' => $totalDevices['totalDevices'],
                'active_devices' => $totalDevices['activeDevices'],
                'inactive_devices' => $totalDevices['totalDevices'] - $totalDevices['activeDevices'],
            ],
            'alarms' => [
                'total_active' => $activeAlarmsCount,
                'warning' => $warningAlarmsCount,
                'critical' => $criticalAlarmsCount,
                'other' => $activeAlarmsCount - ($warningAlarmsCount + $criticalAlarmsCount)
            ],
            'customers' => $customers,
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch dashboard statistics',
            'error' => $e->getMessage()
        ], 500);
    }
}

    public function getAdminActiveDevicesList(){
        try {
            // $token = readHeaderToken();
            $deviceIds = Device::where(['active' => 1])->get()
            ->pluck('id')
            ->flatten()
            ->toArray();


            $activeDevices = $this->customerInfoService->getActiveDevicesList($deviceIds);
            $deviceCount = $this->customerInfoService->getDevicesCount($deviceIds);

            $activeDeviceIds = collect($activeDevices['activeDevices'])->pluck('entityId')->pluck('id')->toArray();

            $getDevices = Device::with('asset')->whereIn('id', $activeDeviceIds)->get(['id', 'name', 'label', 'asset_id', 'customer_id', 'type', 'created_at']);

            $liveDevices = $getDevices->map(function($device){

                $assetName = Asset::where('id', $device->asset_id)->first()->name;

                return [
                    'deviceId' => $device->id,
                    'assetName' => $assetName,
                    'deviceName' => $device->label,
                    'deviceType' => $device->type,
                    'deviceCustomer' => $device->customer->title,
                    'deviceCreatedAt' => $device->created_at ?? 'N/A'
                ];
            });


            return response()->json(['success' => true, 'totalDevices' => $deviceCount['totalDevices'] ?? 0, 'activeDevices' => $deviceCount['activeDevices'] ?? 0, 'data' => $liveDevices]);
        } catch(Exception $e){
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

}
