<?php

namespace App\Http\Controllers;

use App\Models\Categories;
use App\Models\SubCategories;
use App\Models\BankQuestion;
use Illuminate\Http\Request;

class CategoriesController extends Controller
{
    public function index()
    {
        return response()->json(

            Categories::with('subCategories')
                ->orderBy('name')
                ->get()

        );
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:100'
        ]);

        $exists = Categories::whereRaw(
            'LOWER(name) = ?',
            [strtolower($request->name)]
        )->exists();

        if ($exists) {

            return response()->json([
                'success' => false,
                'message' => 'Category already exists'
            ], 400);

        }

        $category = Categories::create([
            'name' => $request->name,
            'created_by' => auth()->user()->user_id
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Category created successfully',
            'data' => $category
        ]);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
        ]);

        $category = Categories::find($id);

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

        $category->update([
            'name' => $request->name,
        ]);

        return response()->json([
            'message' => 'Category updated successfully',
            'data' => $category
        ]);
    }

    public function destroy($id)
    {
        $category = Categories::find($id);

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

        if (
            SubCategories::where(
                'category_id',
                $id
            )->exists()
        ) {
            return response()->json([
                'message' => 'Category cannot be deleted because it still contains sub categories'
            ], 422);
        }

        if (
            BankQuestion::where(
                'category_id',
                $id
            )->exists()
        ) {
            return response()->json([
                'message' => 'Category cannot be deleted because it is already used by questions'
            ], 422);
        }

        $category->delete();

        return response()->json([
            'success' => true,
            'message' => 'Category deleted successfully'
        ]);
    }

}