<?php

namespace $CLASS_NAMESPACE$;

use App\Enums\StatusEnum;
use App\Http\Controllers\Controller;
use $MODULE_NAMESPACE$\$MODULE$\Services\$STUDLY_NAME$Service;
use $MODULE_NAMESPACE$\$MODULE$\Models\$STUDLY_NAME$;
use $MODULE_NAMESPACE$\$MODULE$\Http\Requests\$STUDLY_NAME$Request;
use $MODULE_NAMESPACE$\$MODULE$\Transformers\$STUDLY_NAME$Resource;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Exception;

class $CLASS$ extends Controller
{
    public function __construct(protected $STUDLY_NAME$Service $service) {}

    public function index(Request $request)
    {
         try {
            $queryParams = $this->service->paginateParams($request);

            $$LOWER_NAME$s = $this->service->all($queryParams);     // paginated list
            $summary = $this->service->summary($queryParams); // summary counts

            // If client wants JSON (fetch with Accept: application/json), return API payload
            if ($request->wantsJson()) {
                return response()->json([
                    'data' => $STUDLY_NAME$Resource::collection($$LOWER_NAME$s->items()),
                    'meta' => simple_pagination_meta($$LOWER_NAME$s),
                    'query' => $queryParams,
                    'summary' => $summary,
                    'statuses' => $this->service->statuses(),
                    'status' => 'success',
                ]);
            }


            return Inertia::render('$STUDLY_NAME$/Index', [
                'data' => [
                    'data' => $STUDLY_NAME$Resource::collection($$LOWER_NAME$s->items()),
                    'meta' => simple_pagination_meta($$LOWER_NAME$s),
                    'links' => [
                        'prev' => $$LOWER_NAME$s->previousPageUrl(),
                        'next' => $$LOWER_NAME$s->nextPageUrl(),
                    ],
                    'queryParams' => $queryParams,
                    'summary' => $summary,
                    'statuses' => $this->service->statuses(),
                ],
            ]);
        } catch (Exception $e) {
            debug_log('Error ' . $e->getMessage());

            return Inertia::render('Error/Index');
        }
    }


    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return Inertia::render('$STUDLY_NAME$/Create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store($STUDLY_NAME$Request $request)
    {
        try {
            $item = $this->service->create($request->validated());

            return redirect()->route('$KEBAB_NAME$.index')->with('success', '$STUDLY_NAME$ created successfully.');
        } catch (\Exception $e) {
            debug_log('Error ' . $e->getMessage());
            return redirect()->back()->with('error', 'Failed to create $LOWER_NAME$.');
        }
    }

    /**
     * Show the specific data using id.
     */
    public function show($id)
    {
        try {
            $item = $this->service->getById($id);

            if (!$item) {
                return response()->json([
                    'status' => 'error',
                    'message' => '$STUDLY_NAME$ not found.',
                ], 404);
            }

            return new $STUDLY_NAME$Resource($item);
        } catch (\Exception $e) {
            debug_log('Error ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to load $LOWER_NAME$: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Show the form for editing a specific resource.
     */
    public function edit($id)
    {
        try {
            $item = $this->service->getById($id);

            if (!$item) {
                return redirect()->route('$KEBAB_NAME$.index')->with('error', '$STUDLY_NAME$ not found.');
            }

            return Inertia::render('$STUDLY_NAME$/Edit', [
                '$LOWER_NAME$' => $item,
            ]);
        } catch (\Exception $e) {
            debug_log('Error ' . $e->getMessage());
            return redirect()->route('$KEBAB_NAME$.index')->with('error', 'Failed to load $LOWER_NAME$ for editing.');
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update($STUDLY_NAME$Request $request, $id)
    {
        try {
            $item = $this->service->update($id, $request->validated());

            if (!$item) {
                return redirect()->route('$KEBAB_NAME$.index')->with('error', '$STUDLY_NAME$ not found.');
            }

            return redirect()->route('$KEBAB_NAME$.index')->with('success', '$STUDLY_NAME$ updated successfully.');
        } catch (\Exception $e) {
            debug_log('Error ' . $e->getMessage());
            return redirect()->back()->with('error', 'Failed to update $LOWER_NAME$.');
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, $id)
    {
        try {
            $result = $this->service->delete($id);

            if (!$result) {
                return redirect()->route('$KEBAB_NAME$.index')->with('error', '$STUDLY_NAME$ not found.');
            }

            return redirect()->route('$KEBAB_NAME$.index')->with('success', '$STUDLY_NAME$ deleted successfully.');
        } catch (\Exception $e) {
            debug_log('Error ' . $e->getMessage());
            return redirect()->back()->with('error', 'Failed to delete $LOWER_NAME$.');
        }
    }

    /**
     * Export $LOWER_NAME$s to CSV/PDF
     */
    public function export(Request $request)
    {
        return $this->service->export($request);
    }

    /**
     * Import $LOWER_NAME$s
     */
    public function import(Request $request)
    {
        $message = $this->service->import($request);

        return redirect()->route('$KEBAB_NAME$.index')->with('success', $message);
    }

    /**
     * Download exported file
     */
    public function download($filename)
    {
        return $this->service->download($filename);
    }

    /**
     * Update status for a single $LOWER_NAME$
     */
    public function updateStatus(Request $request, $id)
    {
        try {
            $result = $STUDLY_NAME$::findOrFail($id);


            $statusEnum = StatusEnum::tryFrom((int)$request->input('status'));


            if (!$statusEnum) {
                return redirect()->route('$KEBAB_NAME$.index')->with('error', 'Invalid status selected.');
            }
            $result->update(['status' => $statusEnum->value]);
            return redirect()->route('$KEBAB_NAME$.index')->with('success', '$STUDLY_NAME$ status updated successfully.');

        } catch (\Exception $e) {
            debug_log('Error ' . $e->getMessage());
            return redirect()->back()->with('error', 'Failed to update $LOWER_NAME$ status: ' . $e->getMessage());
        }
    }

    /**
     * Bulk action handler (status updates, etc.)
     */
    public function bulkAction(Request $request)
    {
        try {
            // Validate the request
            $request->validate([
                'type' => ['required', 'string', Rule::in(['update_status'])],
                'select_all' => ['sometimes', 'boolean'],
                'filters' => ['sometimes', 'array'],
                'data' => ['array'],
                // Status update validation
                'data.status' => [
                    'required_if:type,update_status',
                    'integer',
                    Rule::in([0, 1]), // 0 = INACTIVE, 1 = ACTIVE
                ],
            ]);

            $data = $request->input('data', []);
            $type = $request->input('type');
            $ids = $request->input('ids', []);

            // Validate ids based on select_all
            if (!$request->boolean('select_all') && empty($ids)) {
                return redirect()->back()->with('error', 'Please select at least one $LOWER_NAME$.');
            }

            // Handle select_all functionality
            if ($request->boolean('select_all')) {
                // Derive ids from filters server-side
                $filters = $request->input('filters', []);
                $queryParams = array_merge($filters, ['per_page' => null, 'page' => null]);
                $query = $this->service->baseQuery($queryParams);
                $max = (int) config('bulk_actions.max_select_all', 25000);
                $allIds = [];
                $query->select('id')->chunk(1000, function ($chunk) use (&$allIds, $max) {
                    foreach ($chunk as $$LOWER_NAME$) {
                        $allIds[] = $$LOWER_NAME$->id;
                        if (count($allIds) >= $max) {
                            return false; // break out early
                        }
                    }
                });
                $ids = $allIds;
                $data['ids'] = $ids; // ensure handlers get full list
            }

            // Handle status update
            if ($type === 'update_status') {
                // Map numeric status to string values
                // 1 = ACTIVE, 0 = INACTIVE
                $statusMap = [
                    1 => 'ACTIVE',
                    0 => 'INACTIVE',
                ];

                $numericStatus = $data['status'];
                $status = $statusMap[$numericStatus] ?? null;

                if (!$status) {
                    return redirect()->back()->with('error', 'Invalid status value.');
                }

                $result = $this->service->bulkStatusUpdate($status, $ids);

                return redirect()->route('$KEBAB_NAME$.index')->with('success', "Successfully updated {$result['count']} $LOWER_NAME$(s).");
            }

            return redirect()->back()->with('error', 'Unknown bulk action type.');

        } catch (\Exception $e) {
            debug_log('Error ' . $e->getMessage());
            return redirect()->back()->with('error', 'Bulk action failed: ' . $e->getMessage());
        }
    }
}
