<?php

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

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

class DocumentTypeController extends Controller
{

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

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

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

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

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

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

        $type = $type->orderBy('id', 'DESC')
            ->skip($noOfRec * ($currentPage - 1))
            ->take($noOfRec)
            ->get();

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


    public function create()
    {
        //
    }


    public function store(Request $request)
    {
        // Validate the request
        $validator = validator($request->all(), [
            'name' => 'required|string|unique:document_types,name',
        ]);

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

        try {
            // Check for duplicate entry
            $duplicateCheck = DocumentType::where('name', $request->input('name'))->first();

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

            // Create new Document Type
            $type = DocumentType::create(['name' => $request->input('name')]);

            // Prepare response
            return response()->json([
                'success' => true,
                'message' => 'Document Type added successfully.',
                'data' => $type,
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while adding the Document Type: ' . $e->getMessage(),
            ], 500);
        }
    }


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

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

        try {
            // Find the document type by ID
            $type = DocumentType::findOrFail($request->input('id'));

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

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

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

            // Prepare the response
            return response()->json([
                'success' => true,
                'message' => 'Type 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:document_types,id', // Ensure ID exists in the table
        ]);

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

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

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

            // Prepare the response
            return response()->json([
                'success' => true,
                'message' => 'Type 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 type.',
            ], 500);
        }
    }
}
