<?php

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

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\cms\Masters\Port;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class PortController extends Controller
{
    public function index(Request $request)
    {
        $ports = Port::query();

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

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

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

        // Searching based on 'search' keyword (id, name, status)
        if (!empty($request->search)) {
            $search = $request->search;
            $ports->where(function ($query) use ($search) {
                $query->where('id', 'LIKE', "%{$search}%")
                    ->orWhere('name', 'LIKE', "%{$search}%")
                    ->orWhere('status', 'LIKE', "%{$search}%");
            });
        }

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

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

        // Sorting logic
        if (!empty($request->sort_by)) {
            $sortOrder = ($request->sort_order == 1) ? 'asc' : 'desc';
            $ports->orderBy($request->sort_by, $sortOrder);
        } else {
            $ports->orderBy('id', 'desc');
        }

        // Fetch paginated results
        $ports = $ports->skip($noOfRec * ($currentPage - 1))
            ->take($noOfRec)
            ->get();

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




    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Validate the request
        $validator = validator($request->all(), [
            'name' => 'required|string|unique:ports,name',
        ]);

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

        try {
            // Create new Port
            $port = Port::create(['name' => $request->input('name')]);

            return response()->json([
                'success' => true,
                'message' => 'Port Created Successfully',
                'data' => $port,
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while creating the port: ' . $e->getMessage(),
            ], 500);
        }
    }



    public function update(Request $request)
    {
        // Validate the request (only for 'name')
        $validator = validator($request->all(), [
            'name' => 'required|string',
        ]);

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

        try {
            // Find the record by ID
            $type = Port::findOrFail($request->input('id'));  // Assuming 'id' is passed for the record to update

            // Check for duplicate name excluding current ID
            $duplicateCheck = Port::where('name', $request->input('name'))
                ->where('id', '!=', $type->id)  // Avoid checking the current record
                ->first();

            if ($duplicateCheck) {
                return response()->json([
                    'success' => false,
                    'message' => 'Duplicate name "' . $request->input('name') . '" already exists.',
                ], 409);
            }

            // Update name
            $type->update(['name' => $request->input('name')]);

            // Prepare response
            return response()->json([
                'success' => true,
                'message' => 'Port updated successfully.',
                'data' => $type,
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid ID to update.',
            ], 404);
        }
    }


    public function destroy(Request $request)
    {
        // Validate the request
        $validator = validator($request->all(), [
            'id' => 'required|exists:ports,id', // Ensure ID exists in the table
        ]);

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

        try {
            // Find the Port by ID or fail
            $port = Port::findOrFail($request->input('id'));

            // Delete the record
            $port->delete();

            return response()->json([
                'success' => true,
                'message' => 'Port deleted successfully.',
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid ID to delete.',
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while deleting the port.',
            ], 500);
        }
    }
}
