<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\SubjectMaster;
use Illuminate\Http\Request;
use DB;

class SubjectMasterController extends Controller
{
    public function index()
    {

        $list = SubjectMaster::select('_id', 'name', 'icon')->get()->map(function ($item) {
                                        $item->icon = asset('storage/subjects/' . $item->icon);
                                        return $item;
                                    });
        return response()->json([
            'success'   => true,
            'list'      => $list,
        ], 200);
    }

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

        $subject = SubjectMaster::create($request->all());
        return response()->json($subject, 201);
    }

    public function show(SubjectMaster $subjectMaster)
    {
        return response()->json($subjectMaster);
    }

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

        $subjectMaster->update($request->all());
        return response()->json($subjectMaster);
    }

    public function destroy(SubjectMaster $subjectMaster)
    {
        $subjectMaster->delete();
        return response()->json(['message' => 'Deleted successfully']);
    }
}
