<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Models\CustomField;
use App\Service\ActivityService;

class CustomFieldController extends Controller
{
    public function fieldCreateUpdate(Request $request) {
        if (!Auth::check()) return response()->json(['error' => 'Unauthorized'], 401);
        
        // Validate the request data
        $validator = \Validator::make($request->all(), [
            // 'name' => 'required',
            'module_id' => 'required',
            'field_name'=>'required',
            'field_type'=>'required',
            'required_status'=>'required'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->getMessageBag()
            ], 422);
        }

        try {
            $user = Auth::user();
            
            $obj['module_id']=strtolower($request->input('module_id'));
            $obj['label']=$request->input('label');
            $obj['field_name']=strtolower($request->input('field_name'));
            $obj['field_type']=strtolower($request->input('field_type'));
            $obj['required_status']=$request->input('required_status');
            $obj['dropdown_value']=$request->input('dropdown_value');

            if($request['id']>0){
                
                try{
                    
                    $customField = CustomField::findOrFail($request['id']);
                    $customField->update($obj);

                    // Creating Activities
                    $activity=new ActivityService;
                    $activity->activityCreateUpdate('Custom Field',$customField['id'],'Updated');

                } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                    // Return error message in JSON if ID not found
                    return response()->json(['message' => 'Invalid Id to update '], 404);
                }

            }else{

                $customField = CustomField::create($obj);

                // Creating Activities
                $activity=new ActivityService;
                $activity->activityCreateUpdate('Custom Field',$customField['id'],'Created');
            }
            
            
            return response()->json([
                'success' => true,
                'data' => $customField,
                'message'=>'Custom field inserted in module'.$customField['module_id']
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function getCustomFields(Request $request){
        $user = Auth::user();
        $fields=[];
        
        // Get all custom fields of the user's modules.
        $customField=CustomField::where('organisation_id',$user['active_organisation'])
            ->where('is_disabled',0);

        if(isset($request['module_id'])){
            $customField=$customField->where('module_id',$request['module_id']);
        }

        $customField= $customField->get();

        $response=[
            'success'=>'Module fetch successfully',
            'custom_field'=>$customField
        ];

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

    }

    public function delete(Request $request){
        $user=Auth::user();

         // Validate Item
         $validator=validator($request->all(),[
            'id'=>'required',
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {

            try{

                $customField=CustomField::where('organisation_id',$user['active_organisation'])
                    ->where('id',$request['id'])->first();

                $customField['is_disabled']=1;

                $customField->update();

                $response=[
                    'success'=>true,
                    'message'=>'Custom Field Deleted Successfully',
                ];

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                // Return error message in JSON if ID not found
                return response()->json(['message' => 'Invalid Id to update '], 404);
            }

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

}
