<?php

namespace App\Http\Controllers\Admin\Akademik;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Str;

use App\Models\Perpus\KelasKodeModel;
use App\Models\Akademik\AbsensiModel;
use App\Models\Siswa\SiswaModel;

class AbsensiController extends Controller
{
    private $views      = 'admin/akademik/absensi';
    private $url        = 'admin/akademik/absensi';
    private $title      = 'Halaman Absensi Siswa';

    public function __construct()
    {
        createLogActivity();
        // Di isi Construct
        $this->mPerpusKelasKode     = new KelasKodeModel();
        $this->mAkAbsensi           = New AbsensiModel();
        $this->mSiswa              = new SiswaModel();
    }

    // status absensi
    // 0: belum ada absensi
    // 1: hadir
    // 2: tidak hadir

    public function index()
    {

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Absensi Siswa',
        ];

        return view($this->views . "/index", $data);
    }

    public function getAbsensi($tanggal)
    {

        // $tanggal = date("d-m-Y", strtotime($tanggal));

        $data = \DB::table('perpus_kelasKode')
            ->where('perpus_kelasKode.idPSekolah', session()->get('idPSekolah'))
            ->leftJoin('akademik_absensi', function ($join) use ($tanggal) {
                $join->on('perpus_kelasKode.id', '=', 'akademik_absensi.idPKKode')
                    ->whereDate('akademik_absensi.date', '=', $tanggal);
            })
            ->join('perpus_kelas', 'perpus_kelasKode.idPKelas', '=', 'perpus_kelas.id')
            ->join('perpus_jurusan', 'perpus_kelasKode.idPJurusan', '=', 'perpus_jurusan.id')
            ->select(
                'perpus_kelasKode.id as kelas_id',
                \DB::raw('COALESCE(MIN(akademik_absensi.date), "' . $tanggal . '") as tanggal'),
                \DB::raw('CONCAT(perpus_kelas.nama, " ", perpus_jurusan.nama, " ", perpus_kelasKode.nama) as nama_kelas'),
                \DB::raw('count(akademik_absensi.id) as jumlah_kehadiran'),
                \DB::raw('SUM(CASE WHEN akademik_absensi.idStatus = 1 THEN 1 ELSE 0 END) as jumlah_hadir'),
                \DB::raw('SUM(CASE WHEN akademik_absensi.idStatus = 2 THEN 1 ELSE 0 END) as jumlah_tidak_hadir')
            )
            ->groupBy('perpus_kelasKode.id', 'perpus_kelasKode.nama')
            ->get()
            ->map(function($item) use ($tanggal) {
                // Menyimpan kelas_id
                $kelas_id = $item->kelas_id;
                
                // Membuat tombol HTML
                $buttonHtml = "<a href='".url("{$this->url}/create/{$kelas_id}/{$tanggal}")."'><button type='button' class='btn btn-primary btn-sm' title='Detail Data'>Detail</button></a>";
                
                if($item->jumlah_kehadiran > 0){
                    
                    $status = '<span class="text-primary">Ada</span>';
                }else{
                    $status = '<span class="text-warning">Tidak Ada</span>';
                }
                
                // Mengembalikan array numerik tanpa kelas_id
                return [
                    $item->tanggal,
                    $item->nama_kelas,
                    $item->jumlah_hadir,
                    $item->jumlah_tidak_hadir,
                    $status,
                    $buttonHtml
                ];
            });

        $response = ['data' => $data];
        echo json_encode($response);
    }

    public function create($idPKKode=null, $tanggal=null)
    {
        // $kelas = $this->mPerpusKelasKode->where('id', $idPKKode)->first();
        // $tanggal = date("d-m-Y", strtotime($tanggal));
        
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Absensi Kelas',
            'idKelas'       => $idPKKode,
            // 'kelas'         => $kelas,
            'tanggal'       => $tanggal,
        ];
        
        return view($this->views . "/show", $data);
    }

    function getAbsensiForm($idPKKode = null, $tanggal = null)
    {
        // Fetch attendance data for a specific class code and date.
        $absensi = $this->mAkAbsensi->where('idPKKode', $idPKKode)->where('date', $tanggal)->first();

        // Define initial conditions based on the user's role.
        if (session()->get('role') == 1) {
            // For role 1, fetch all students in the given class with a specific status.
            $where = [
                'idPKKode' => $idPKKode,
                'idMStatus' => 1,  // assuming idMStatus refers to an active student status or similar
            ];
        } else {
            // For other roles, restrict students to those within the same school and specific conditions.
            $where = [
                'idPSekolah' => session()->get('idPSekolah'),
                'idPPeriode' => session()->get('idPPeriode'),
                'idPKKode' => $idPKKode,
                'idMStatus' => 1,
                'idPPkelas' => 1,
                'idPPStatus' => 1,
            ];
        }

        // Fetch all students based on the conditions defined above.
        $siswa = $this->mSiswa->where($where)->get();

        // Check if there is existing attendance data.
        if ($absensi) {
            // Get all attendance records for the specific class and date.
            $absensiSiswa = $this->mAkAbsensi->where('idPKKode', $idPKKode)
                                            ->where('date', $tanggal)
                                            ->get(['idSiswa', 'idStatus'])->keyBy('idSiswa');

            // Map student data with attendance status.
            $data = $siswa->map(function ($item) use ($absensiSiswa) {
                return [
                    'i' => '',
                    'id' => $item->id,
                    'nisn' => $item->nisn,
                    'nama' => $item->nama,
                    // 'statusAbsensi' => $absensiSiswa->has($item->id) ? $absensiSiswa[$item->id]['idStatus'] : 0  // Default status 0 if not found
                    'statusAbsensi' => $absensiSiswa[$item->id]['idStatus']
                ];
            });
        } else {
            // If no attendance data, map student data without status.
            $data = $siswa->map(function ($item) {
                return [
                    'i' => '',
                    'id' => $item->id,
                    'nisn' => $item->nisn,
                    'nama' => $item->nama,
                    'statusAbsensi' => 0  // No attendance data found
                ];
            });
        }

        // Return data as JSON.
        return response()->json(['data' => $data, 'status' => $absensi ? 1 : 0]);
    }


    public function store(Request $request)
    {
        $kodekelas  = $this->mPerpusKelasKode->where('id', $request->valKelas)->first();
        $absensi      = $this->mAkAbsensi->where('idPKKode', $request->valKelas)->where('date',$request->valTanggal)->first();

        $cekId = $request->input('cekId', []);
        $cekVal = $request->input('cekVal', []);
        
        // status absensi
        // 0: belum ada absensi
        // 1: hadir
        // 2: tidak hadir

        foreach ($cekId as $idSiswa => $value) {
            // Dapatkan status siswa; 'on' berarti hadir (1), '2' berarti tidak hadir
            $status = isset($cekVal[$idSiswa]) && $cekVal[$idSiswa] == 'on' ? 1 : 2;

            // Simpan atau update data absensi siswa
            $dataAbsensi = [
                'idPSekolah'        => session()->get('idPSekolah'),
                'idPJurusan'        => $kodekelas->jurusan->id,
                'idPKelas'          => $kodekelas->kelas->id,
                'idPKKode'          => $kodekelas->id,
                'idPPeriode'        => session()->get('idPPeriode'),
                'idSiswa'           => $idSiswa,
                'idStatus'          => $status,
                'date'              => $request->valTanggal,
            ];

            $absensi = $this->mAkAbsensi
                ->where('idPKKode', $kodekelas->id)
                ->where('date', $request->valTanggal)
                ->where('idSiswa', $idSiswa)
                ->first();

            if ($absensi) {
                $absensi->update($dataAbsensi);
            } else {
                $this->mAkAbsensi->create($dataAbsensi);
            }
        }


        if(isset($absensi)){
            return redirect("$this->url")->with('sukses', 'Absensi berhasil di Perbarui');
        }else{
            return redirect("$this->url")->with('sukses', 'Absensi berhasil di Tambahkan');
        }
    }
}
