<?php

namespace App\Http\Controllers;

use App\Models\DeviceMaster;
use App\Models\MfmMeter;
use App\Models\MfmParameter;
use App\Models\Plant;
use Illuminate\Http\Request;

class MfmParameterController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }
    public function get_mfm_parameterid(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw   = env('API_AUTH_PW');
        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser . ':' . $expectedPw;

        if ("Bearer " . $expectedToken != $header_auth) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!'
            ], 403);
        }

        $plantCode  = $request->header('plant-code');

        if (!$plantCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant Code value can't be empty"
            ], 404);
        }

        $plant = Plant::where('code', $plantCode)->first();

        if (!$plant)
        {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant Code '{$plantCode}' not found!"
            ], 404);
        }


        // $sequences = MfmMeter::where('plant_id', $plant->id)
        //     ->whereNotNull('sequence')
        //     ->distinct()
        //     ->orderBy('sequence', 'asc')
        //     ->pluck('sequence');
        $sequences = MfmMeter::where('plant_id', $plant->id)
            ->whereNotNull('sequence')
            ->pluck('sequence')
            ->unique()
            ->map(fn($s) => is_numeric($s) ? (int) $s : $s)
            ->sort()
            ->values();

        if ($sequences->isEmpty())
        {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'No sequences found for the given plant.'
            ], 404);
        }


        return response()->json([
            'status_code' => 'SUCCESS',
            'status_description' => $sequences
        ], 200);

    }

    public function get_mfm_parameter(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw   = env('API_AUTH_PW');
        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser . ':' . $expectedPw;

        if ("Bearer " . $expectedToken != $header_auth) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!'
            ], 403);
        }

        $plantCode  = $request->header('plant-code');
        $mfmParameterSeq = $request->header('mfm-meter-sequence');
        $deviceName = $request->header('device-name');

        if (!$plantCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant Code value can't be empty"
            ], 404);
        }
        else if (!$mfmParameterSeq) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Mfm Parameter sequence value can't be empty"
            ], 404);
        }
        else if (!$deviceName) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Device name value can't be empty"
            ], 404);
        }

        $plant = Plant::where('code', $plantCode)->first();

        $device = DeviceMaster::where('name', $deviceName)->first();

        if (!$plant)
        {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant Code '{$plantCode}' not found!"
            ], 404);
        }

        // Find mfm_meter by sequence and plant_id
        $mfmMeter = MfmMeter::where('sequence', trim($mfmParameterSeq))
            ->where('plant_id', $plant->id)
            ->where('device_master_id', $device->id)
            ->first();

        if (!$mfmMeter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "MFM Meter with sequence '{$mfmParameterSeq}' not found for plant code '{$plantCode}'"
            ], 404);
        }

        // Now fetch mfm_parameters for this plant and meter
        $mfmParameters = MfmParameter::where('plant_id', $plant->id)
            ->where('mfm_meter_id', $mfmMeter->id)
            ->where('device_master_id', $device->id)
            ->get(['register_id', 'byte_to_convert', 'type_to_convert', 'decimal_to_display']);

            $transformed = $mfmParameters->map(function ($item) {
            $array = $item->toArray();
            foreach ($array as $key => $value) {
                if (is_null($value)) {
                    $array[$key] = "";
                }
            }
              return $array;
            });

            //..if want to send all values in string
        //     $transformed = $mfmParameters->map(function ($item) {
        //     $array = $item->toArray();
        //     foreach ($array as $key => $value) {
        //         // Always cast to string (empty string if null)
        //         $array[$key] = is_null($value) ? "" : strval($value);
        //     }
        //     return $array;
        // });


        if ($transformed->isEmpty()) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "No MFM parameters found for the specified plant,meter and device name."
            ], 404);
        }

        // Success: return list
        return response()->json([
            'status_code' => 'SUCCESS',
            'status_description' => $transformed
       ], 200);

    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
