<?php

namespace App\Http\Controllers;

use App\Models\ModuleList;
use Illuminate\Http\Request;

class ModuleChartController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    public function get_moduleChart(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);
        }

        $moduleName = $request->header('module-name');

        if (empty($moduleName))
        {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Module Name can't be empty!"
            ], 404);
        }

        $exists = ModuleList::where('module_name', $moduleName)->exists();

        if (!$exists) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Module Name '{$moduleName}' not found in system!"
            ], 404);
        }

        // Fetch all unique dashboard names for the given module_name
        // $dashboardNames = ModuleList::where('module_name', $moduleName)
        //     ->distinct()
        //     ->pluck('dashboard_name');
        $dashboardNames = ModuleList::where('module_name', $moduleName)
        ->orderBy('created_at', 'asc')
        ->get()
        ->unique('dashboard_name')
        ->pluck('dashboard_name')
        ->values(); // reset array keys


       return response()->json([
            'status_code' => 'SUCCESS',
            'status_description' => $dashboardNames
        ], 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)
    {
        //
    }
}
