<?php

namespace App\Http\Controllers;

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

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

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

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

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

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

        if ($headerValue != 'Module List') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid value for 'module-name' header!"
            ], 404);
        }

        $uniqueModules = ModuleList::select('module_name', 'created_at')
            ->orderBy('created_at', 'asc')
            ->get()
            ->unique('module_name')
            ->pluck('module_name')
            ->values();

             if ($uniqueModules->isEmpty()) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Module names not found'
            ], 404);
        }


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

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

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