<?php

namespace App\Http\Controllers;

use App\Models\DetailMataKuliah;
use Illuminate\Http\Request;

class DetailMataKuliahController extends Controller
{
    // Middleware to protect specific routes
    public function __construct()
    {
        // Apply 'auth' middleware only to specified methods
        $this->middleware('auth', ['only' => ['store', 'update', 'destroy', 'index', 'show']]);
    }

    // $jadwalkuliah = JadwalKuliah::with(['jurusan', 'tahun_ajar', 'semester', 'kelas', 'kelaskuliah'])->get();

    // Retrieve all records from the m_matakuliah table
    public function index()
    {
        $detailmatakuliah = DetailMataKuliah::with(['detailmatakuliah']);
        return response()->json($detailmatakuliah);
    }

    // Retrieve a specific record based on kd_matakuliah
    public function show($kd_matakuliah)
    {
        $detailmatakuliah = DetailMataKuliah::find($kd_matakuliah);

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

        return response()->json($detailmatakuliah);
    }

    // Create a new matakuliah
    public function store(Request $request)
    {
        $this->validate($request, [
            'kode_kelas' => 'required',
            'nim' => 'required',
            'kd_jurusan' => 'required',
            'kd_tahun_ajar' => 'required',
            'kd_semester' => 'required',
            // other validation rules
        ]);

        $detailmatakuliah = DetailMataKuliah::create($request->all());

        return response()->json(['message' => 'Matakuliah created successfully', 'data' => $detailmatakuliah]);
    }

    // Update a matakuliah
    public function update(Request $request, $kd_matakuliah)
    {
        $detailmatakuliah = DetailMataKuliah::find($kd_matakuliah);

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

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

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

    // Delete a matakuliah
    public function destroy($kd_matakuliah)
    {
        $detailmatakuliah = DetailMataKuliah::find($kd_matakuliah);

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

        $detailmatakuliah->delete();

        return response()->json(['message' => 'Matakuliah deleted successfully']);
    }
}
