<?php

namespace App\Http\Controllers\Siswa;

use App\Http\Controllers\Controller;
use App\Models\Absensi;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PresensiController extends Controller
{
    public function index(): View
    {
        $siswa = auth()->user();
        $siswaProfile = $siswa->siswaProfile;

        if (!$siswaProfile) {
            abort(403, 'Profil siswa Anda tidak ditemukan.');
        }

        // Fetch all attendance records for this student sorted by date
        $absensiList = Absensi::where('siswa_id', $siswa->id)
            ->with('mataPelajaran')
            ->orderBy('tanggal', 'asc')
            ->get();

        // Group by subject
        $grouped = $absensiList->groupBy('mata_pelajaran_id');
        $presensiData = [];

        foreach ($grouped as $mapelId => $records) {
            $mapel = $records->first()->mataPelajaran;
            if (!$mapel) {
                continue;
            }

            // Create a 16-element array representing the 16 columns in the table:
            // 0-6: Pertemuan 1-7
            // 7: UTS
            // 8-14: Pertemuan 8-14
            // 15: UAS
            $mappedData = array_fill(0, 16, '');

            foreach ($records as $index => $rec) {
                if ($index >= 16) {
                    break;
                }

                // Map status enum to UI symbols
                $symbol = '';
                if ($rec->status === 'hadir') {
                    $symbol = '✓';
                } elseif ($rec->status === 'izin') {
                    $symbol = 'i';
                } elseif ($rec->status === 'sakit') {
                    $symbol = '+';
                } elseif ($rec->status === 'alpa') {
                    $symbol = '×';
                }

                $mappedData[$index] = $symbol;
            }

            $presensiData[] = [
                'mapel' => $mapel->nama_mapel,
                'data' => $mappedData
            ];
        }

        return view('siswa.presensi', [
            'presensiData' => $presensiData,
            'siswaKelas' => $siswaProfile->kelas,
        ]);
    }
}
