<?php

namespace App\Http\Controllers\APIS\AdminApi;

use App\Http\Controllers\Controller;
use App\Http\Requests\CreateDeviceRequest;
use App\Models\Device;
use App\Models\Asset;
use App\Models\DeviceProfileMaster;
use App\Services\DeviceService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Exception;
use Illuminate\Support\Facades\Validator;



class DeviceController extends Controller
{

    protected $deviceService;

    public function __construct(DeviceService $deviceService)
    {
        $this->deviceService = $deviceService;
    }


    public function createOrUpdateDevice(Request $request)
    {
        try {

            $deviceNameExists = Device::where('name', $request->name)->first();
            if (empty($request->id) && $deviceNameExists) {
                // return response()->json(['status' => 'error','message' => 'Device name already exists'],400);
                return jsonResponseWithErrorMessage('Device name already exists', 400);
            }

            $assetNameExists = Asset::where('name', $request->name)->first();
            if ($assetNameExists) {
                return jsonResponseWithErrorMessage('Name already exists', 400);
            }

            $deviceProfileName = DeviceProfileMaster::where('id',$request->deviceProfileId)->first();

            $deviceData = [
                'id' => $request->id ?? null,
                'name'       => $request->name ?? null,
                'type'       => $deviceProfileName['name'] ?? null,
                'label'      => $request->label ?? null,
                'version'    => $request->version ?? 1,
                'customerId'    => $request->customerId ?? 1,
                'additionalInfo' => $request->additionalInfo ?? [],
                'deviceData' => [
                    'configuration' => ['type' => 'DEFAULT'],
                    'transportConfiguration' => [
                        'type' => 'DEFAULT',
                        'powerMode' => $request->transportConfiguration['powerMode'] ?? 'PSM',
                        'psmActivityTimer' => $request->transportConfiguration['psmActivityTimer'] ?? 9007199254740991,
                        'edrxCycle' => $request->transportConfiguration['edrxCycle'] ?? 9007199254740991,
                        'pagingTransmissionWindow' => $request->transportConfiguration['pagingTransmissionWindow'] ?? 9007199254740991,
                    ]
                ],
                'deviceProfileId'    => $request->deviceProfileId ?? 1,
                'asset_id'    => $request->asset_id ?? 'null',

            ];

            // Optional Fields

            // dd($request->id);
            // Handle updating existing devices
            if (!empty($request->id)) {
                $deviceData['id'] = $request->id;

                $deviceNameExists = Device::where('name', $request->name)->where('id','!=',$request->id)->first();
                if ($deviceNameExists) {
                    return response()->json(['status' => 'error','message' => 'Device name already exists'],400);
                }
            }
            if (!empty($request->firmwareId)) {
                $deviceData['firmwareId'] = $request->firmwareId;
            }
            if (!empty($request->softwareId)) {
                $deviceData['softwareId'] = $request->softwareId;
            }

            // dd($request->all());
            // Call Service to create/update device
            if (empty($request->id)) {
                $apiResponse = $this->deviceService->createOrUpdateDevice($deviceData);
            }

            // Log::info("API Response: " . json_encode($apiResponse));

            $deviceProfileName = DeviceProfileMaster::where('id', $request->deviceProfileId)->first();

            // Store device in the database
            $device = Device::updateOrCreate(
                ['id' => $apiResponse['id']['id'] ?? $request->id],
                [
                    'entity_type' => 'DEVICE',
                    'created_time' => now()->timestamp,
                    'customer_id' => $request->customerId ?? null,
                    'name' => $request->name ?? null,
                    'type' => $deviceProfileName['name'] ?? null,
                    'label' => $request->label ?? null,
                    'asset_id' => $request->asset_id ?? null,
                    'speed_limit' => $request->speed_limit ?? null,
                    'torque_limit' => $request->torque_limit ?? null,
                    'power_limit' => $request->power_limit ?? null,
                    'device_profile_id' => $request->deviceProfileId ?? null,
                    'firmware_id' => $request->firmware_id ?? null,
                    'software_id' => $request->software_id ?? null,
                    'version' => $request->version ?? 1,
                    'tenant_id' => $request->tenant_id ?? null,
                    'device_data' => json_encode($request->device_data ?? []),
                    'additional_info' => $request->additionalInfo
                ]
            );

            return jsonResponseWithSuccessMessage(
                !empty($request->id) ? 'Device updated successfully' : 'Device created successfully',
                ['device' => $device]
            );
        } catch (Exception $e) {
            Log::error("Error: " . $e->getMessage());

            $errorResponse = json_decode($e->getMessage(), true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return jsonResponseWithErrorMessage($errorResponse['message'] ?? 'Something went wrong', 400, $errorResponse);
            }

            return jsonResponseWithErrorMessage($e->getMessage(), 500);
        }
    }



    // public function listDevices(Request $request)
    // {
    //     try {
    //         $devices = Device::with('deviceProfile','customer');

    //         return jsonResponseWithSuccessMessage('Devices fetched successfully', [
    //             'devices' => $devices
    //         ]);
    //     } catch (Exception $e) {
    //         Log::error("An error occurred: " . $e->getMessage());
    //         return jsonResponseWithErrorMessage($e->getMessage(), 500);
    //     }
    // }

    public function listDevices(Request $request)
{
    try {
        $devices = Device::with('deviceProfile', 'customer')->orderBy('created_at', 'desc')->get()->map(function ($device) {
            $deviceData = $device->toArray();
            unset($deviceData['device_profile'], $deviceData['customer']); // remove full relations

            $deviceData['device_profile_name'] = $device->deviceProfile?->name;
            $deviceData['customer_name'] = $device->customer?->name;

            return $deviceData;
        });

        return jsonResponseWithSuccessMessage('Devices fetched successfully', [
            'devices' => $devices
        ]);
    } catch (Exception $e) {
        Log::error("An error occurred: " . $e->getMessage());
        return jsonResponseWithErrorMessage($e->getMessage(), 500);
    }
}


    public function deleteDevice(Request $request)
    {

        try {
            $validator = Validator::make($request->all(), [

                'device_id' => 'required|string',
            ]);
            if ($validator->fails()) {
                return jsonResponseWithErrorMessage($validator->errors()->first(), 400);
            }
            $deviceId = $request->input('device_id');

            $response = $this->deviceService->deleteDevice(['deviceId' => $deviceId]);


            $Device = Device::where('id', $deviceId)->first();
            if ($Device) {
                $Device->delete();
            }

            return jsonResponseWithSuccessMessage('Device deleted successfully', ['api_response' => $response]);
        } catch (Exception $e) {
            Log::error("An error occurred: " . $e->getMessage());
            $errorResponse = json_decode($e->getMessage(), true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return jsonResponseWithErrorMessage($errorResponse['message'] ?? 'Something went wrong', 400, $errorResponse);
            }

            return jsonResponseWithErrorMessage($e->getMessage(), 500);
        }
    }


    public function devicelistCustomer($customerId)
    {
        try {
            $devices = Device::with('deviceProfile:id,name', 'customer:id,name')
                ->where('customer_id', $customerId)
                ->orderBy('created_at','desc')
                ->get()
                ->map(function ($device) {
                    $deviceArray = $device->toArray();

                    unset($deviceArray['device_profile'], $deviceArray['customer']);

                    $deviceArray['customer_name'] = optional($device->customer)->name;
                    $deviceArray['device_profile_name'] = optional($device->deviceProfile)->name;

                    return $deviceArray;
                });

            if ($devices->isEmpty()) {
                return response()->json(['message' => 'No devices found for this customer ID'], 200);
            }

            return jsonResponseWithSuccessMessage('Devices fetched successfully', [
                'devices' => $devices
            ]);
        } catch (Exception $e) {
            Log::error("An error occurred in customer device listing: " . $e->getMessage());
            return jsonResponseWithErrorMessage($e->getMessage(), 500);
        }
    }



}
