<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Pelajaran;
use App\Models\AbsenMapel;
use App\Models\Siswa;

class AbsensiMapelController extends Controller
{
    public function index()
    {
        $data_mapel = Pelajaran::orderBy('mata_pelajaran', 'ASC')->get();
        return view('absensi.mapel', compact('data_mapel'));
    }

    public function proses(Request $request)
    {
        $request->validate([
            'id_siswa' => 'required',
            'keterangan' => 'required',
            'id_mapel' => 'required',
        ]);

        AbsenMapel::create([
            'tgl_absen' => now(),
            'keterangan' => $request->keterangan,
            'id_siswa' => $request->id_siswa,
            'id_mapel' => $request->id_mapel,
        ]);

        $siswa = Siswa::find($request->id_siswa);
        $mapel = Pelajaran::find($request->id_mapel);

        return response()->json([
            'success' => true,
            'message' => 'Absen berhasil disimpan!',
            'data' => [
                'nama' => $siswa->nama ?? 'Tidak Diketahui',
                'mapel' => $mapel->mata_pelajaran ?? '-',
                'keterangan' => $request->keterangan,
            ]
        ]);
    }
}
