<?php

namespace App\Http\Controllers;

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

class TenderTypeController extends Controller
{
    /**
     * Display all records
     */
   public function index(Request $request): JsonResponse

{

    try {

        // Get query parameters

        $perPage = $request->get('per_page', 10);

        $search = $request->get('search', '');

        $withTrashed = $request->get('with_trashed', false);

        // Start query

        $query = TenderType::with('ledger');

        // Include soft deleted records if requested

        if ($withTrashed) {

            $query->withTrashed();

        }



        // Apply search filter

        if ($search) {

            $query->where(function ($q) use ($search) {

                $q->where('TnT_Code', 'like', "%{$search}%")

                  ->orWhere('TnT_Name', 'like', "%{$search}%");

            });

        }



        // Apply ordering

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



        // Get paginated results

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



        return response()->json([

            'success' => true,

            'data' => $tenders->items(),

            'meta' => [

                'current_page' => $tenders->currentPage(),

                'last_page' => $tenders->lastPage(),

                'per_page' => $tenders->perPage(),

                'total' => $tenders->total(),

                'from' => $tenders->firstItem(),

                'to' => $tenders->lastItem(),

            ]

        ]);



    } catch (\Exception $e) {

        return response()->json([

            'success' => false,

            'message' => 'Failed to retrieve Tender Types.',

            'error' => config('app.debug') ? 'Something went wrong. Please try again later.' : null

        ], 500);

    }

}


    public function all(Request $request): JsonResponse
{
   try {
     $search = $request->get('search', '');
     $withTrashed = $request->get('with_trashed', false);
     $query = TenderType::with('ledger');
     // Include soft deleted records if requested
     if ($withTrashed) {
       $query->withTrashed();
    }
     // Apply search filter
     if ($search) {
       $query->where(function ($q) use ($search) {
         $q->where('TnT_Code', 'like', "%{$search}%")
         ->orWhere('TnT_Name', 'like', "%{$search}%");
      });
    }
     // Order
     $data = $query->orderBy('TnT_ID', 'desc')->get();
     return response()->json([
       'success' => true,
       'data' => $data,
       'total' => $data->count()
    ]);
  } catch (\Exception $e) {
     return response()->json([
       'success' => false,
       'message' => 'Failed to retrieve Tender Types.',
       'error' => config('app.debug') ? 'Something went wrong. Please try again later.' : null
    ], 500);
  }
}

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'TnT_Code' => 'nullable|string|max:20|unique:tender_type,TnT_Code',
            'TnT_Name' => 'required|string|max:50',
            'Lg_Id'    => 'nullable|exists:ledger_master,Lg_Id',
                 'Is_Active' => 'nullable|boolean',
        ]);

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

        $tender = TenderType::create($request->all());
        $tender->load('ledger');

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


    public function show($id)
    {
       $tender = TenderType::with('ledger')->find($id);

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

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

    public function update(Request $request, $id)
    {
        $tender = TenderType::find($id);

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

        $validator = Validator::make($request->all(), [
            'TnT_Code' => 'nullable|string|max:20|unique:tender_type,TnT_Code,' . $id . ',TnT_ID',
            'TnT_Name' => 'required|string|max:50',
            'Lg_Id' => 'nullable|exists:ledger_master,Lg_Id',
            'Is_Active' => 'sometimes|boolean',
        ]);

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

        $tender->update($request->all());
        $tender->load('ledger');

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


    public function destroy($id)
    {
        $tender = TenderType::find($id);

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

        $tender->delete();

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


    public function restore($id)
    {
        $tender = TenderType::withTrashed()->find($id);

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

        $tender->restore();

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

    public function forceDelete(string $id): JsonResponse
    {
        try {
            $newTenderWork = TenderType::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
    {
        // Validate request
        $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 = TenderType::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 = TenderType::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);
        }
    }
}
