<?php

namespace App\Http\Controllers;

use App\Models\Krs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Validator;
use Illuminate\Support\Facades\DB;

class KrsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['only' => ['store', 'update', 'destroy', 'index', 'show']]);
    }

    // Menampilkan KRS berdasarkan NIM
    public function show($id)
    {
        // $id_company = request()->header('id_company');
        // $id_company = 1;  // Misalnya id_company diambil dari session atau parameter lain
        
        $data = DB::table('kelas_perkuliahan as a')
            ->select(
                'a.kd_jurusan', 'a.kd_tahun_ajar', 'a.kd_semester', 'a.kd_kelas', 'a.nidn',
                'a.kd_matakuliah', 'a.jml_pertemuan', 'b.jurusan', 'c.tahun_ajar', 'd.semester',
                'e.nama_kelas', 'f.nama as nama_dosen', 'g.nim', 'h.nama_lengkap', 'j.matakuliah',
                'j.kd_jenis_matakuliah', 'j.SKS', 'i.sks_tm', 'i.sks_praktikum', 'i.sks_pkl', 'i.sks_simulasi'
            )
            ->join('m_jurusan as b', 'a.kd_jurusan', '=', 'b.kd_jurusan')
            ->join('m_tahun_ajar as c', 'a.kd_tahun_ajar', '=', 'c.kd_tahun_ajar')
            ->join('m_semester as d', 'a.kd_semester', '=', 'd.kd_semester')
            ->join('m_kelas as e', function($join) {
                $join->on('a.kd_kelas', '=', 'e.kode_kelas')
                    ->on('a.kd_tahun_ajar', '=', 'e.kd_tahun_ajar')
                    ->on('a.kd_semester', '=', 'e.kd_semester');
            })
            ->join('m_dosen as f', 'a.nidn', '=', 'f.nidn')
            ->join('m_kelas_detail as g', function($join) {
                $join->on('a.kd_kelas', '=', 'g.kode_kelas')
                    ->on('a.kd_tahun_ajar', '=', 'g.kd_tahun_ajar')
                    ->on('a.kd_semester', '=', 'g.kd_semester');
            })
            ->join('m_mahasiswa as h', 'g.nim', '=', 'h.nim')
            ->join('m_matakuliah as j', 'a.kd_matakuliah', '=', 'j.kd_matakuliah')
            ->join('m_detail_matakuliah as i', 'a.kd_matakuliah', '=', 'i.kd_matakuliah')
            ->where('g.nim', $id)
            // ->where('a.kd_jurusan', $id_company)
            ->groupBy('a.kd_matakuliah')  // Menambahkan group by di sini
            ->orderBy('a.kd_tahun_ajar', 'asc')
            ->orderBy('a.kd_semester', 'asc')
            ->get();


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

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