<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Pelanggaran;
use Illuminate\Http\Request;

class PelanggaranController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        // Jika user adalah guru, batasi data berdasarkan user_id
        $query = Pelanggaran::with(['santri', 'kelas', 'user'])->orderByDesc('created_at');

        if ($user->role === 'guru') {
            $query->where('user_id', $user->id);
        }
        // Jika user adalah santri, batasi data berdasarkan santri_id
        elseif ($user->santri) {
            $query->where('santri_id', $user->santri->id);
        }

        $pelanggarans = $query->get()->map(function ($item) {
            return [
                'id' => $item->id,
                'santri_id' => $item->santri_id,
                'nama_santri' => $item->santri->nama ?? null,
                'kelas_id' => $item->kelas_id,
                'nama_kelas' => $item->kelas->nama_kelas ?? null,
                'jenis_pelanggaran' => $item->jenis_pelanggaran,
                'hukuman' => $item->hukuman,
                'keterangan_hukuman' => $item->keterangan_hukuman,
                'hukuman_selesai' => $item->hukuman_selesai,
                'user_id' => $item->user_id,
                'nama_penginput' => $item->user->name ?? null,
                'created_at' => $item->created_at->toDateTimeString(),
                'updated_at' => $item->updated_at->toDateTimeString(),
            ];
        });

        return response()->json([
            'success' => true,
            'message' => 'Data pelanggaran berhasil diambil.',
            'data' => $pelanggarans,
        ]);
    }
}
