<?php

namespace App\Http\Controllers;

use App\Models\FunctionType;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Throwable;

class FunctionTypeController extends Controller
{
    // GET all
    public function index(Request $request)
    {
        try {
            $queryValue = $request->input('query');
            $isvisible = $request->input('isvisible');

            $query = FunctionType::query();

            if ($queryValue) {
                $query->where(function ($q) use ($queryValue) {
                    $q->where('UpGrp', 'like', $queryValue . '%');
                });
            }

            if ($isvisible !== null) {
                $query->where('isvisible', $isvisible);
            }

            $functionTypes = $query->get();

            return response()->json([
                'status'  => 'success',
                'message' => 'Function types fetched successfully',
                'data'    => $functionTypes
            ]);
        } catch (Throwable $e) {
            Log::error('Fetch Error: ' . $e->getMessage());
            return response()->json([
                'status'  => 'error',
                'message' => 'Unable to fetch function types',
                'error'   => $e->getMessage(),
            ], 500);
        }
    }

    // GET one
    public function show($id)
    {
        try {
            $data = FunctionType::find($id);

            if (!$data) {
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Function type not found'
                ], 404);
            }

            return response()->json([
                'status'  => 'success',
                'message' => 'Function type fetched successfully',
                'data'    => $data
            ]);
        } catch (Throwable $e) {
            Log::error('Show Error: ' . $e->getMessage());
            return response()->json([
                'status'  => 'error',
                'message' => 'Unable to fetch function type',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    // CREATE
    public function store(Request $request)
   {
    try {

        // ✅ Validation with Limits
        $validator = Validator::make($request->all(), [
            'Fnc_Title'   => 'nullable|string|max:50',
            'Fnc_Desc'    => 'nullable|string|max:255',
            'GrCod'       => 'nullable|string|max:30',
            'UpGrp'       => 'nullable|string|max:30',
            'GrSrn'       => 'nullable|string|max:30',
            'GrStt'       => 'nullable|string|max:30',
            'isvisible'   => 'nullable|integer|in:0,1',
            'Description' => 'nullable|string|max:255',
            'Menu_Links'  => 'nullable|string|max:150',
        ]);

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }

        // Default GrStt
        $grstt = $request->has('GrStt') ? $request->input('GrStt') : '1';

        // Default GrSrn
        $grsrn = $request->has('GrSrn')
            ? $request->input('GrSrn')
            : FunctionType::where('GrStt', $grstt)->count() + 1;

        // Format Code
        $prefix = str_pad($grsrn, 2, '0', STR_PAD_LEFT);
        $codeFormat = $prefix . '000000';

        $data = [
            'Fnc_Title'    => $request->input('Fnc_Title'),
            'Fnc_Desc'     => $request->input('Fnc_Desc'),
            'Description'  => $request->input('Description'),
            'GrCod'        => $request->input('GrCod', $codeFormat),
            'UpGrp'        => $request->input('UpGrp', $codeFormat),
            'GrSrn'        => (string) $grsrn,
            'GrStt'        => $grstt,
            'isvisible'    => $request->input('isvisible', 1),
            'Menu_Links'   => $request->input('Menu_Links'),
        ];

        $type = FunctionType::create($data);

        return response()->json([
            'status'  => 'success',
            'message' => 'Function type created successfully',
            'data'    => $type
        ], 201);

    } catch (ValidationException $e) {
        return response()->json([
            'status'  => 'error',
            'message' => 'Validation failed',
            'errors'  => $e->errors()
        ], 422);

    } catch (Throwable $e) {
        Log::error('Create Error: ' . $e->getMessage());

        return response()->json([
            'status'  => 'error',
            'message' => 'Unable to create function type',
            'error'   => $e->getMessage()
        ], 500);
    }
}

    // UPDATE
    public function update(Request $request, $id)
    {
        try {
            $type = FunctionType::find($id);

            if (!$type) {
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Function type not found'
                ], 404);
            }

            $data = $request->validate([
           'Fnc_Title'   => 'sometimes|nullable|string|max:50',
            'Fnc_Desc'    => 'sometimes|nullable|string|max:255',
            'GrCod'       => 'sometimes|nullable|string|max:30',
            'UpGrp'       => 'sometimes|nullable|string|max:30',
            'GrSrn'       => 'sometimes|nullable|string|max:30',
            'GrStt'       => 'sometimes|nullable|string|max:30',
            'isvisible'   => 'sometimes|nullable|integer|in:0,1',
            'Description' => 'sometimes|nullable|string|max:255',
            'Menu_Links'  => 'sometimes|nullable|string|max:150',
            'isvisible'    => 'sometimes|nullable|integer|in:0,1',
            ]);

            $type->update($data);

            return response()->json([
                'status'  => 'success',
                'message' => 'Function type updated successfully',
                'data'    => $type
            ]);
        } catch (ValidationException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (Throwable $e) {
            Log::error('Update Error: ' . $e->getMessage());
            return response()->json([
                'status'  => 'error',
                'message' => 'Unable to update function type',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    // TOGGLE VISIBILITY
    public function toggleVisibility($id)
    {
        try {
            $type = FunctionType::find($id);

            if (!$type) {
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Function type not found'
                ], 404);
            }

            $type->update([
                'isvisible' => $type->isvisible == 1 ? 0 : 1
            ]);

            $status = $type->isvisible == 1 ? 'Active' : 'Inactive';

            return response()->json([
                'status'  => 'success',
                'message' => 'Function type visibility toggled successfully',
                'data'    => [
                    'Fnc_Id'    => $type->Fnc_Id,
                    'isvisible' => $type->isvisible,
                    'status'    => $status
                ]
            ]);
        } catch (Throwable $e) {
            Log::error('Toggle Visibility Error: ' . $e->getMessage());
            return response()->json([
                'status'  => 'error',
                'message' => 'Unable to toggle function type visibility',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    // DELETE (soft delete)
    public function destroy($id)
    {
        try {
            $type = FunctionType::find($id);

            if (!$type) {
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Function type not found'
                ], 404);
            }

            $type->delete();

            return response()->json([
                'status'  => 'success',
                'message' => 'Function type deleted successfully'
            ]);
        } catch (Throwable $e) {
            Log::error('Delete Error: ' . $e->getMessage());
            return response()->json([
                'status'  => 'error',
                'message' => 'Unable to delete function type',
                'error'   => $e->getMessage()
            ], 500);
        }
    }
}
