<?php

namespace App\Http\Controllers\Api\cms\Masters;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\cms\Masters\ContainerType;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;



class ContainerTypeController extends Controller

{

   public function index(Request $request)
    {
        $query = ContainerType::query();

        // Filtering based on 'id'
        if (!empty($request->id) && $request->id > 0) {
            $query->where('id', $request->id);
        }

        // Filtering based on 'status' (only 0 or 1)
        if (isset($request->status) && in_array($request->status, [0, 1])) {
            $query->where('status', $request->status);
        }

        // Searching based on multiple fields
        if (!empty($request->search)) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('type', 'LIKE', "%{$search}%")
                    ->orWhere('internal_dimension', 'LIKE', "%{$search}%")
                    ->orWhere('cubic_capacity', 'LIKE', "%{$search}%")
                    ->orWhere('cargo_weight', 'LIKE', "%{$search}%")
                    ->orWhere('id', 'LIKE', "%{$search}%");
            });
        }

        // Sorting functionality
        $validSortColumns = ['id', 'type', 'internal_dimension', 'cubic_capacity', 'cargo_weight', 'status'];
        $sortBy = in_array($request->sort_by, $validSortColumns) ? $request->sort_by : 'id';
        $sortOrder = ($request->sort_order == 1) ? 'asc' : 'desc';
        $query->orderBy($sortBy, $sortOrder);

        // Counting total records
        $count = $query->count();

        // Pagination with 'noofrec' and 'currentpage'
        $noOfRec = $request->noofrec ?? 100;
        $currentPage = $request->currentpage ?? 1;

        $containerTypes = $query->skip($noOfRec * ($currentPage - 1))
            ->take($noOfRec)
            ->get();

        // Response structure
        return response()->json([
            'success' => true,
            'total' => $count,
            'data' => $containerTypes,
        ]);
    }


    public function create()
    {

        //

    }

    public function store(Request $request)
    {
        // Validate input
        $validator = Validator::make($request->all(), [
            'type' => 'required|string',
            'type_size' => ['required', 'integer'],
        ]);

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

        try {
            // Check for duplicate entry only for type
            $existingType = ContainerType::where('type', $request->type)->first();

            if ($existingType) {
                return response()->json([
                    'success' => false,
                    'message' => 'Duplicate entry: Type ' . $existingType->type . ' already exists!'
                ], 409);
            }

            // Create new record
            $container = ContainerType::create([
                'type' => $request->type,
                'type_size' => $request->type_size,
                'internal_dimension' => $request->internal_dimension,
                'door_opening' => $request->door_opening,
                'cubic_capacity' => $request->cubic_capacity,
                'cargo_weight' => $request->cargo_weight,
                'entryby' => Auth::id()
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Data Created Successfully',
                'data' => $container
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Something went wrong!',
                'error' => $e->getMessage()
            ], 500);
        }
    }


    public function show(Request $request)
    {
        try {
            // Validate the request
            $validatedData = $request->validate([
                'id' => 'required|integer|exists:container_types,id'
            ]);

            // Retrieve the id from input
            $id = $validatedData['id'];

            // Fetch the container type
            $containertype = ContainerType::where('id', $id)->where('status', 0)->first();

            // Check if the container type is found
            if (!$containertype) {
                return response()->json([
                    'success' => false,
                    'message' => 'Container type not found or inactive.',
                ], 404);
            }

            return response()->json([
                'success' => true,
                'message' => 'Data retrieved successfully',
                'data' => $containertype,
            ], 200);
        } catch (\Illuminate\Database\QueryException $e) {
            // Handle database errors
            return response()->json([
                'success' => false,
                'message' => 'Database error: ' . $e->getMessage(),
            ], 500);
        } catch (\Illuminate\Validation\ValidationException $e) {
            // Handle validation errors
            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $e->errors(),
            ], 422);
        } catch (\Exception $e) {
            // Handle general errors
            return response()->json([
                'success' => false,
                'message' => 'An error occurred: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function update(Request $request)
    {
        // Validate input (including validation for type_size with 'ft' suffix)
        $validator = Validator::make($request->all(), [
            'id' => 'required|exists:container_types,id', // Ensure ID exists in the table
            'type' => 'required|string',
            'type_size' => ['required', 'integer'],
        ]);

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

        try {
            // Find the existing container type
            $container = ContainerType::findOrFail($request->id);

            // Update the record
            $container->update([
                'type' => $request->type,
                'type_size' => $request->type_size,
                'internal_dimension' => $request->internal_dimension,
                'door_opening' => $request->door_opening,
                'cubic_capacity' => $request->cubic_capacity,
                'cargo_weight' => $request->cargo_weight,
                'entryby' => Auth::id()
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Data Updated Successfully',
                'data' => $container
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Something went wrong!',
                'error' => $e->getMessage()
            ], 500);
        }
    }



    public function destroy(Request $request)
    {
        // Validate Item
        $validator = validator($request->all(), [
            'id' => 'required|exists:container_types,id',
        ]);

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

        try {
            // Find the container type and delete it
            $type = ContainerType::findOrFail($request->input('id'));
            $type->delete();

            return response()->json([
                'success' => true,
                'message' => 'Type deleted successfully.'
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['success' => false, 'message' => 'Invalid ID provided.'], 404);
        }
    }


    public function updateStatus(Request $request)
    {
        // Validate Item
        $validator = validator($request->all(), [
            'id' => 'required'
        ]);

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

        try {
            // Fetch the container type by ID
            $container_type = ContainerType::findOrFail($request['id']); // Use findOrFail() to throw ModelNotFoundException if not found

            // Toggle status
            if ($container_type['status'] == 1) {
                $container_type['status'] = 0;
                $msg = "Inactive Successfully";
            } else {
                $container_type['status'] = 1;
                $msg = "Active Successfully";
            }

            // Save changes to the database
            $container_type->save();

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