<?php

namespace App\Http\Controllers;

use App\Models\GrantCatMaster;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class GrantCatMasterController extends Controller
{
    /* ================= LIST ================= */
  public function index(Request $request)
{
    try {
        $perPage = $request->get('per_page', 25);
        $search = $request->get('search', '');
        $withTrashed = $request->get('with_trashed', false);

        $query = GrantCatMaster::orderBy('GC_Id', 'desc');

        // Include soft deleted if requested
        if ($withTrashed) {
            $query->withTrashed();
        }

        // Search filter
        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('GC_Name', 'like', "%{$search}%")
                  ->orWhere('GC_Id', 'like', "%{$search}%");
            });
        }

        // Pagination or all
        if ($perPage === 'all') {
            $data = $query->get();
        } else {
            $data = $query->paginate((int) $perPage);
        }

        return response()->json([
            'status' => true,
            'message' => 'Grant Category fetched successfully',
            'data' => $data
        ], 200);

    } catch (\Exception $e) {
        return response()->json([
            'status' => false,
            'message' => 'Something went wrong',
            'error' => $e->getMessage()
        ], 500);
    }
}
public function all()
{
    try {
        return response()->json([
            'status' => true,
            'data' => GrantCatMaster::latest('GC_Id')->get()
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'status' => false,
            'message' => $e->getMessage()
        ], 500);
    }
}


    /* ================= STORE ================= */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'GC_Name' => 'nullable|string',
            'GC_Code' => 'nullable|string',
        ]);

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

        $data = GrantCatMaster::create($request->all());

        return response()->json([
            'status' => true,
            'message' => 'Grant Category Created Successfully',
            'data' => $data
        ]);
    }

    /* ================= SHOW ================= */
    public function show($id)
    {
        $data = GrantCatMaster::find($id);

        if (!$data) {
            return response()->json([
                'status' => false,
                'message' => 'Data Not Found'
            ], 404);
        }

        return response()->json([
            'status' => true,
            'data' => $data
        ]);
    }

    /* ================= UPDATE ================= */
    public function update(Request $request, $id)
    {
        $data = GrantCatMaster::find($id);

        if (!$data) {
            return response()->json([
                'status' => false,
                'message' => 'Data Not Found'
            ], 404);
        }

        $validator = Validator::make($request->all(), [
            'GC_Name' => 'nullable|string',
            'GC_Code' => 'nullable|string',
        ]);

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

        $data->update($request->all());

        return response()->json([
            'status' => true,
            'message' => 'Grant Category Updated Successfully',
            'data' => $data
        ]);
    }

    /* ================= DELETE ================= */
    public function destroy($id)
    {
        $data = GrantCatMaster::find($id);

        if (!$data) {
            return response()->json([
                'status' => false,
                'message' => 'Data Not Found'
            ], 404);
        }

        $data->delete();

        return response()->json([
            'status' => true,
            'message' => 'Grant Category Deleted Successfully'
        ]);
    }

public function restore(string $id)
    {
        try {
            $grantCategory = GrantCatMaster::withTrashed()->find($id);

            if (!$grantCategory) {
                return response()->json([
                    'success' => false,
                    'message' => 'Grant category not found'
                ], 404);
            }

            if (!$grantCategory->trashed()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Grant category is not deleted'
                ], 400);
            }

            $grantCategory->restore();

            return response()->json([
                'success' => true,
                'message' => 'Grant category restored successfully',
                'data' => $grantCategory
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to restore grant category',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get trashed grant categories.
     */
    public function trashed()
    {
        try {
            $grantCategories = GrantCatMaster::onlyTrashed()->orderBy('deleted_at', 'desc')->get();

            return response()->json([
                'success' => true,
                'message' => 'Trashed grant categories retrieved successfully',
                'data' => $grantCategories
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve trashed grant categories',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Force delete grant category.
     */
    public function forceDelete(string $id)
    {
        try {
            $grantCategory = GrantCatMaster::withTrashed()->find($id);

            if (!$grantCategory) {
                return response()->json([
                    'success' => false,
                    'message' => 'Grant category not found'
                ], 404);
            }

            $grantCategory->forceDelete();

            return response()->json([
                'success' => true,
                'message' => 'Grant category permanently deleted successfully'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to permanently delete grant category',
                'error' => $e->getMessage()
            ], 500);
        }
    }

}
