<?php

namespace App\Http\Controllers;

use App\Models\CompletionTemplate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException;

/**
 * @group Template Management
 *
 * APIs for managing completion letter templates
 * @authenticated
 */
class CompletionTemplateController extends Controller
{
    /**
     * Display all completion templates
     *
     * @authenticated
     * @return JsonResponse
     */
    public function index(): JsonResponse
    {
        try {
            $templates = CompletionTemplate::latest()->get();

            return response()->json([
                'success' => true,
                'data' => $templates
            ]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching templates',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Store new completion template
     *
     * @authenticated
     * @param Request $request
     * @return JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'greeting' => 'required|string|max:255',
                'content' => 'required|string',
                'closing' => 'required|string|max:255',
                'sign_person' => 'required|string|max:255',
                'position_name' => 'required|string|max:255',
                'signature' => 'nullable|string'
            ]);

            $template = CompletionTemplate::create($validated);

            return response()->json([
                'success' => true,
                'message' => 'Template berhasil dibuat',
                'data' => $template
            ], 201);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error creating template',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Display specific completion template
     *
     * @authenticated
     * @param string $id
     * @return JsonResponse
     */
    public function show(string $id): JsonResponse
    {
        try {
            $template = CompletionTemplate::findOrFail($id);

            return response()->json([
                'success' => true,
                'data' => $template
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Template not found'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving template',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update completion template
     *
     * @authenticated
     * @param Request $request
     * @param string $id
     * @return JsonResponse
     */
    public function update(Request $request, string $id): JsonResponse
    {
        try {
            $template = CompletionTemplate::findOrFail($id);

            $validated = $request->validate([
                'greeting' => 'sometimes|string|max:255',
                'content' => 'sometimes|string',
                'closing' => 'sometimes|string|max:255',
                'sign_person' => 'sometimes|string|max:255',
                'position_name' => 'sometimes|string|max:255',
                'signature' => 'nullable|string'
            ]);

            $template->update($validated);

            return response()->json([
                'success' => true,
                'message' => 'Template berhasil diperbarui',
                'data' => $template
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Template not found'
            ], 404);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error updating template',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete completion template
     *
     * @authenticated
     * @param string $id
     * @return JsonResponse
     */
    public function destroy(string $id): JsonResponse
    {
        try {
            $template = CompletionTemplate::findOrFail($id);
            $template->delete();

            return response()->json([
                'success' => true,
                'message' => 'Template berhasil dihapus'
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Template not found'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error deleting template',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
