<?php

namespace App\Http\Controllers;

use App\Models\EmdbgType;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;

class EmdbgTypeController extends Controller
{

public function index(Request $request): JsonResponse
{
    try {
        
        $perPage = $request->get('per_page', 10);
        $search = $request->get('search', '');
        $withTrashed = $request->get('with_trashed', false);

        
        $query = EmdbgType::query();

        if ($withTrashed) {
            $query->withTrashed();
        }

        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('EBT_Code', 'like', "%{$search}%")
                  ->orWhere('EBT_Name', 'like', "%{$search}%")
                  ->orWhere('percentage', 'like', "%{$search}%");
            });
        }

        $query->orderBy('EBT_Id', 'desc');

        $records = $query->paginate($perPage);

        return response()->json([
            'success' => true,
            'message' => 'Records retrieved successfully.',
            'data' => $records->items(),
            'meta' => [
                'current_page' => $records->currentPage(),
                'last_page' => $records->lastPage(),
                'per_page' => $records->perPage(),
                'total' => $records->total(),
                'from' => $records->firstItem(),
                'to' => $records->lastItem(),
            ]
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Failed to retrieve records.',
            'error' => config('app.debug') ? 'Something went wrong. Please try again later.' : null
        ], 500);
    }
}

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'EBT_Code' => 'nullable|string|max:20|unique:emdbg_type,EBT_Code',
            'EBT_Name' => 'required|string|max:50',
            'Percentage' => 'nullable|integer',
                'Is_Active' => 'nullable|boolean',
        ]);

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

        $record = EmdbgType::create($request->all());

        return response()->json([
            'success' => true,
            'message' => 'Record created successfully',
            'data' => $record
        ], 201);
    }

 
    public function show($id)
    {
        $record = EmdbgType::find($id);

        if (!$record) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $record
        ]);
    }

 
    public function update(Request $request, $id)
    {
        $record = EmdbgType::find($id);

        if (!$record) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found'
            ], 404);
        }

        $validator = Validator::make($request->all(), [
            'EBT_Code' => 'nullable|string|max:20|unique:emdbg_type,EBT_Code,' . $id . ',EBT_Id',
            'EBT_Name' => 'required|string|max:50',
            'Percentage' => 'nullable|integer',
            	'Is_Active' => 'sometimes|boolean',
        ]);

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

        $record->update($request->all());

        return response()->json([
            'success' => true,
            'message' => 'Record updated successfully',
            'data' => $record
        ]);
    }


    public function destroy($id)
    {
        $record = EmdbgType::find($id);

        if (!$record) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found'
            ], 404);
        }

        $record->delete();

        return response()->json([
            'success' => true,
            'message' => 'Record deleted successfully'
        ]);
    }

    public function restore($id)
    {
        $record = EmdbgType::withTrashed()->find($id);

        if (!$record) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found'
            ], 404);
        }

        $record->restore();

        return response()->json([
            'success' => true,
            'message' => 'Record restored successfully',
            'data' => $record
        ]);
    }



    public function forceDelete(string $id): JsonResponse
    {
        try {
            $newTenderWork = EmdbgType::withTrashed()->find($id);

            if (!$newTenderWork) {
                return response()->json([
                    'success' => false,
                    'message' => 'New Tender Work not found.'
                ], 404);
            }

            $newTenderWork->forceDelete();

            return response()->json([
                'success' => true,
                'message' => 'New Tender Work permanently deleted successfully.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to permanently delete New Tender Work.',
                'error' => config('app.debug') ? 'Something went wrong. Please try again later.' : null
            ], 500);
        }
    }


    private function transformTenderWork($tenderWork): array
    {
        return [
            'tend_work_id' => $tenderWork->tend_work_id,
            'work_code' => $tenderWork->work_code,
            'work_name' => $tenderWork->work_name,
            'created_at' => $tenderWork->created_at ? $tenderWork->created_at->format('Y-m-d H:i:s') : null,
            'updated_at' => $tenderWork->updated_at ? $tenderWork->updated_at->format('Y-m-d H:i:s') : null,
            'deleted_at' => $tenderWork->deleted_at ? $tenderWork->deleted_at->format('Y-m-d H:i:s') : null,
            'is_deleted' => !is_null($tenderWork->deleted_at)
        ];
    }


    public function bulkStore(Request $request): JsonResponse
    {

        $validator = Validator::make($request->all(), [
            'works' => 'required|array|min:1',
            'works.*.work_code' => 'nullable|string|max:20',
            'works.*.work_name' => 'required|string|max:255'
        ], [
            'works.required' => 'Works array is required.',
            'works.*.work_name.required' => 'Work Name is required for all items.',
            'works.*.work_code.max' => 'Work Code must not exceed 20 characters.',
            'works.*.work_name.max' => 'Work Name must not exceed 255 characters.'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $createdWorks = [];

            foreach ($request->works as $workData) {
                $newTenderWork = EmdbgType::create([
                    'work_code' => $workData['work_code'] ?? null,
                    'work_name' => $workData['work_name']
                ]);

                $createdWorks[] = $this->transformTenderWork($newTenderWork);
            }

            return response()->json([
                'success' => true,
                'message' => count($createdWorks) . ' New Tender Work(s) created successfully.',
                'data' => $createdWorks
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create New Tender Works.',
                'error' => config('app.debug') ? 'Something went wrong. Please try again later.' : null
            ], 500);
        }
    }


    public function active(): JsonResponse
    {
        try {
            $activeWorks = EmdbgType::orderBy('work_name', 'asc')->get();

            $transformedData = $activeWorks->map(function ($item) {
                return $this->transformTenderWork($item);
            });

            return response()->json([
                'success' => true,
                'message' => 'Active New Tender Works retrieved successfully.',
                'data' => $transformedData
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve Active New Tender Works.',
                'error' => config('app.debug') ? 'Something went wrong. Please try again later.' : null
            ], 500);
        }
    }
}
