<?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
{
        
 public function index(Request $request)
{
    try {
        $queryValue = $request->input('query');
            $isvisible = $request->input('isvisible');
            $modCode = $request->input('Mod_Code');

        $query = FunctionType::with('action', 'genVoucherNo');

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

        if ($modCode) {
            $query->where('Mod_Code', $modCode);
        }

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

        $functionTypes = $query->orderBy('GrCod', 'asc')->get();

        $functionTypes->each(function ($item) {
            if ($item->action) {
                $item->action->setAppends([]);
            }
        });

        return response()->json([
            'status'  => 'success',
            'message' => 'Function types fetched successfully',
            'data'    => $functionTypes
        ]);
    } catch (Throwable $e) {
        Log::error('Fetch Error: ' . 'Something went wrong. Please try again later.');
        return response()->json([
            'status'  => 'error',
            'message' => 'Unable to fetch function types',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage(),
        ], 500);
    }
}

    
    public function show($id)
    {
        try {
            $data = FunctionType::with('action', 'genVoucherNo')->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: ' . 'Something went wrong. Please try again later.');
            return response()->json([
                'status'  => 'error',
                'message' => 'Unable to fetch function type',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }


   public function store(Request $request)
{
    try {
        
        $validator = Validator::make($request->all(), [
            'Mod_Code'    => 'nullable|string|max:4',
            'Fnc_Title'   => 'nullable|string|max:50',
            'Act_Id'      => 'nullable|exists:action_master,Act_Id',
            'gvn_no'      => 'nullable|exists:gen_voucher_no,gvn_no',
            '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',
            'Is_Quick_Action'  => 'nullable|boolean|in:0,1',
            'Description' => 'nullable|string|max:255',
            'Menu_Links'  => 'nullable|string|max:150',
        ]);

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

        
        $validated = $validator->validated();

        
        $modCode = $request->input('Mod_Code');
        $fncTitle = $request->input('Fnc_Title');
        $fncDesc = $request->input('Fnc_Desc');
        $description = $request->input('Description');
        $menuLinks = $request->input('Menu_Links');
        $actId = $request->input('Act_Id');
        $gvn_no = $request->input('gvn_no');
        $grstt = $request->input('GrStt', '1');
        $isvisible = $request->input('isvisible', 1);
        $isQuickAction = $request->input('Is_Quick_Action', 0);

        
        $grsrn = $request->input('GrSrn');
        if (!$grsrn) {
            $grsrn = FunctionType::where('GrStt', $grstt)->count() + 1;
        }

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

        
        $upGrp = $request->input('UpGrp', $codeFormat);
        $grCod = $request->input('GrCod', $codeFormat);

        $data = [
            'Mod_Code' => $modCode,
            'Fnc_Title' => $fncTitle,
            'Fnc_Desc' => $fncDesc,
            'Description' => $description,
            'GrCod' => $grCod,
            'UpGrp' => $upGrp,
            'GrSrn' => (string) $grsrn,
            'GrStt' => $grstt,
            'isvisible' => $isvisible,
            'Is_Quick_Action' => $isQuickAction,
            'Menu_Links' => $menuLinks,
            'Act_Id' => $actId,
            'gvn_no' => $gvn_no,
        ];

        $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: ' . 'Something went wrong. Please try again later.');
        return response()->json([
            'status'  => 'error',
            'message' => 'Unable to create function type',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 500);
    }
}


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([
            'Mod_Code'    => 'sometimes|nullable|string|max:4',
            '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',
            'Is_Quick_Action'  => 'sometimes|nullable|boolean',
            'Description' => 'sometimes|nullable|string|max:255',
            'Menu_Links'  => 'sometimes|nullable|string|max:150',
            'Act_Id'      => 'sometimes|nullable|exists:action_master,Act_Id',
            'gvn_no'      => 'sometimes|nullable|exists:gen_voucher_no,gvn_no',
        ]);

        if ($request->has('Is_Quick_Action')) {
            $data['Is_Quick_Action'] = $request->Is_Quick_Action ? 1 : 0;
        }

        $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: ' . 'Something went wrong. Please try again later.');
        return response()->json([
            'status'  => 'error',
            'message' => 'Unable to update function type',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 500);
    }
}

    
    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: ' . 'Something went wrong. Please try again later.');
            return response()->json([
                'status'  => 'error',
                'message' => 'Unable to toggle function type visibility',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    
    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: ' . 'Something went wrong. Please try again later.');
            return response()->json([
                'status'  => 'error',
                'message' => 'Unable to delete function type',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }
}
