<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\ReportModule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class ReportModuleController extends Controller
{
    public function index(Request $request)
    {
        //
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page',PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        $data = ReportModule::with(['category'])
        ->where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            $query->where('name', 'like', '%' . $keyword . '%');
        });

        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }

        $data = $data->paginate($perPage);
        return response()->json($data);
    }

    public function show(){

    }

    public function store(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'name' => [
                'required',
                'min:2',
                Rule::unique('report_modules')->whereNull('deleted_at')
            ]
        ]);

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], 422);
        }

        DB::beginTransaction();

        try {

            $data = ReportModule::create($request->all());

            DB::commit();

            return response()->json([
                'message' => 'Record Successfully added!',
                'status' => 'success',
            ],201);

        } catch (Throwable $e) {
            DB::rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ], 422);
        }
    }

    public function update(Request $request, int $id)
    {
        $data = ReportModule::where('id', $id)->first();

        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }

        $validator = Validator::make($request->all(),
            [
                'name' => [
                    'required',
                    'min:2',
                    Rule::unique('report_modules')->ignore($id)->whereNull('deleted_at')
                ]
            ]
        );

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], 422);
        }

        DB::beginTransaction();

        try {

            $data->fill($request->all());
            $data->save();

            $data->touch();

            DB::commit();

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ],201);

        } catch (Throwable $e) {
            DB::rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ], 422);
        }
    }

    public function destroy(int $id)
    {
        $data = ReportModule::find($id);
        if(!$data)
        {
            return response()->json(['message' => "Record not found!"],422);
        }
        DB::beginTransaction();
        try {
            $data->delete();
            DB::commit();
            return response()->json(['message' => "Record successfully deleted!"],201);
        }
        catch(Throwable $e) {
            DB::rollback();
            return response()->json(['message' => "Unable to process request. Please contact system administrator.",
            'data' => $e->getMessage()
        ],422);
        }
    }

    public function listByCategory()
    {
        $modules = ReportModule::with('category')
            ->orderBy('sort') // sort reports
            ->get()
            ->groupBy('category_id');

        // Restructure into category + reports format
        $data = $modules->map(function ($items) {
            return [
                'category' => $items->first()->category, // category info
                'reports'  => $items->values(),          // all reports under this category
            ];
        });

        // Sort categories by their `sort` field
        $sorted = $data->sortBy(function ($group) {
            return $group['category']->sort ?? 0;
        })->values(); // reset keys

        return response()->json($sorted);
    }
}
