<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\GetDataApiController;
use App\Models\Kelompok;
use App\Models\Periode;
use Illuminate\Http\Request;

class DosenController extends Controller
{

    public function getDosen(Request $request)
    {
        $keyword    = $request->q;
        $getDosen   = GetDataApiController::getDosen();

        $total_count = 0;
        $incomplete_results =  true;

        $periode = Periode::where('status', 1)->first();

        $items = [];
        if (empty($getDosen)) {

            $items = array();

        } else {
            $no = 0;
            foreach ($getDosen['data'] as $key => $item) {

                if(str_contains(strtolower($item['nm_sdm']), strtolower($keyword))){
                    $jumlah_bimbingan = Kelompok::where('id_sdm', $item['id_sdm'])
                                        ->where('periode_id', $periode->periode_id)
                                        ->where('status_hapus', 0)
                                        ->where('kirim', 1)
                                        ->whereYear('created_at', $periode->nama)
                                        ->count();

                    $slot_tersisa = max(0, 15 - $jumlah_bimbingan);
                    $status_slot = $slot_tersisa == 0 ? '<span style="color: red; font-weight: bold;">(Slot Bimbingan Penuh)</span>' : "(Slot Bimbingan: $slot_tersisa slot)";

                    $itemData = [
                        'id' => encrypt($item['id_sdm'].'_'.$item['nm_sdm'].'_'.$item['nidn']),
                        'full_name' => $item['nm_sdm'],
                        // 'description' => $item['prodi'] . '<span style="margin-left: 2em">-</span><i style="margin-left: 2em">(Slot Bimbingan: ' . (10-$jumlah_bimbingan) . ' slot)</i>',
                        'description' => $item['prodi'] . '<span style="margin-left: 2em">-</span><i style="margin-left: 2em">' . $status_slot . '</i>',
                        'nidn' => $item['nidn'],
                        'bimbingan_count' => $jumlah_bimbingan,
                        'disabled' => $jumlah_bimbingan >= 15 ? true : false,
                    ];

                    $items[] = $itemData;

                    $total_count = $total_count + 1;
                }
            }
        }

        $data = [
            'total_count' => $total_count,
            'incomplete_results' => false,
            'items' => $items,
        ];

        // dd($data);
        return response()->json($data);
        // return response($data, 200);
    }
}