<?php

namespace App\Http\Controllers;

use App\Exports\SiswaExport;
use App\Imports\SiswaImport;
use App\Models\Guru;
use App\Models\JawabanKuesioner;
use App\Models\Pengaduan;
use App\Models\Riwayat;
use App\Models\Rujukan;
use App\Models\User;
use App\Models\Siswa;
use App\Models\Spesialis;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class SiswaController extends Controller
{
    public function index()
    {
        if (Auth::check()) {
            foreach (Auth::user()->roles as $role) {
                if (in_array($role->name, ['WaliKelas', 'GuruBK', 'KepalaSekolah', 'GuruPengajar', 'Admin'])) {
                    $userId = Auth::id();
                    $guru = Guru::where('id_user', $userId)->first();

                    $siswas = $guru
                        ? Siswa::where('id_guru', $guru->id_guru)->get()
                        : Siswa::all(); // Admin bisa lihat semua

                    return view('siswa.index', [
                        'siswas' => $siswas,
                        'gurus' => Guru::all() // Tambahkan daftar semua guru untuk fitur chat
                    ]);
                } elseif ($role->name == 'Siswa') {
                    $userId = Auth::id();
                    $siswa = Siswa::where('id_user', $userId)->first();
                    $pengaduanIds = Pengaduan::where('id_user', $siswa->id_user)->pluck('id_pengaduan_bk');
                    $riwayat = Riwayat::whereIn('id_pengaduan_bk', $pengaduanIds)->get();

                    return view('siswa.index', [
                        'siswas' => collect([$siswa]),
                        'riwayat' => $riwayat,
                        'gurus' => Guru::all() // ini supaya daftar guru BK tetap bisa dipakai chat
                    ]);
                } elseif ($role->name == 'Spesialis') {
                    $userId = Auth::id();
                    $spesialis = Spesialis::where('id_user', $userId)->first();

                    if ($spesialis) {
                        $rujukans = Rujukan::where('tujuan_rujukan', $spesialis->spesialis)
                            ->with('siswa')
                            ->get();

                        $siswas = $rujukans->pluck('siswa')->filter();

                        return view('siswa.index', [
                            'siswas' => $siswas,
                            'gurus' => Guru::all()
                        ]);
                    }
                }
            }
        }
    }

    public function create()
    {
        $data['siswas'] = Siswa::pluck('name', 'id');
        return view(
            'siswa.create',
            $data
        );
    }

    public function store(Request $request)
    {
        $validate = $request->validate([
            'nama_siswa' => 'required|max:150',
            'nis' => 'required|max:255',
            'tempat_lahir' => 'required|max:150',
            'tanggal' => 'required|date',
            'jenis_kelamin' => 'required|max:100',
            'agama' => 'required|max:100',
            'pendik_sebelumnya' => 'max:100',
            'jmlh_sodara' => 'max:100',
            'alamat' => 'required|max:100',
            'nama_ayah' => 'max:100',
            'nama_ibu' => 'max:100',
            'pekerjaan_ayah' => 'max:100',
            'pekerjaan_ibu' => 'max:100',
            'wali_siswa' => 'max:100',
            'kelas' => 'required|max:150',
            'tahun_pelajaran' => 'required|max:100',
            'id_guru' => 'required',
        ]);

        $user = new User();
        $user->name = $validate['nama_siswa'];
        $user->username = $validate['nis'];
        $user->password = Hash::make('konseling25');
        $user->save();

        $siswa = Siswa::create([

            'nama_siswa' => $validate['nama_siswa'],
            'nis' => $validate['nis'],
            'tempat_lahir' => $validate['tempat_lahir'],
            'tanggal' => $validate['tanggal'],
            'jenis_kelamin' => $validate['jenis_kelamin'],
            'agama' => $validate['agama'],
            'pendik_sebelumnya' => $validate['pendik_sebelumnya'],
            'jmlh_sodara' => $validate['jmlh_sodara'],
            'alamat' => $validate['alamat'],
            'nama_ayah' => $validate['nama_ayah'],
            'nama_ibu' => $validate['nama_ibu'],
            'pekerjaan_ayah' => $validate['pekerjaan_ayah'],
            'pekerjaan_ibu' => $validate['pekerjaan_ibu'],
            'wali_siswa' => $validate['wali_siswa'],
            'kelas' => $validate['kelas'],
            'tahun_pelajaran' => $validate['tahun_pelajaran'],
            'id_guru' => $validate['id_guru'],
            'id_user' => $user->id,
        ]);

        $user->assignRole('siswa');

        $notificaton = array(
            'message' => 'Data siswa berhasil ditambahkan!',
            'alert-type' => 'success'
        );

        if ($request->save == true) {
            return redirect()->route('siswa.index')->with($notificaton);
        } else
            return redirect()->route('siswa.create')->with($notificaton);
    }

    public function edit(string $id_siswa)
    {
        $data['siswa'] = Siswa::findOrFail($id_siswa);
        $data['siswas'] = Siswa::all();
        $data['guru'] = Guru::pluck('name', 'id');

        return view('siswa.edit', $data);
    }

    public function update(Request $request, string $id_siswa)
    {
        $siswa = Siswa::findOrFail($id_siswa);

        $validate = $request->validate([

            'nama_siswa' => 'required|max:150',
            'nis' => 'required|max:255',
            'tempat_lahir' => 'required|max:150',
            'tanggal' => 'required|date',
            'jenis_kelamin' => 'required|max:100',
            'agama' => 'required|max:100',
            'pendik_sebelumnya' => 'max:100',
            'jmlh_sodara' => 'max:100',
            'alamat' => 'required|max:100',
            'nama_ayah' => 'max:100',
            'nama_ibu' => 'max:100',
            'pekerjaan_ayah' => 'max:100',
            'pekerjaan_ibu' => 'max:100',
            'wali_siswa' => 'max:100',
            'kelas' => 'required|max:150',
            'tahun_pelajaran' => 'required|max:100',
            'id_guru' => 'required',
        ]);

        $siswa->update([

            'nama_siswa' => $validate['nama_siswa'],
            'nis' => $validate['nis'],
            'tempat_lahir' => $validate['tempat_lahir'],
            'tanggal' => $validate['tanggal'],
            'jenis_kelamin' => $validate['jenis_kelamin'],
            'agama' => $validate['agama'],
            'pendik_sebelumnya' => $validate['pendik_sebelumnya'],
            'jmlh_sodara' => $validate['jmlh_sodara'],
            'alamat' => $validate['alamat'],
            'nama_ayah' => $validate['nama_ayah'],
            'nama_ibu' => $validate['nama_ibu'],
            'pekerjaan_ayah' => $validate['pekerjaan_ayah'],
            'pekerjaan_ibu' => $validate['pekerjaan_ibu'],
            'wali_siswa' => $validate['wali_siswa'],
            'kelas' => $validate['kelas'],
            'tahun_pelajaran' => $validate['tahun_pelajaran'],
            'id_guru' => $validate['id_guru'],
        ]);

        $notificaton = array(
            'message' => 'Data siswa berhasil diperbaharui!',
            'alert-type' => 'success'
        );

        return redirect()->route('siswa.index')->with($notificaton);
    }
    public function destroy(string $id_siswa)
    {
        $siswa = Siswa::findOrFail($id_siswa);

        $siswa->delete();

        $notificaton = array(
            'message' => 'Data siswa berhasil dihapus!',
            'alert-type' => 'success'
        );

        return redirect()->route('siswa.index')->with($notificaton);
    }

    public function export()
    {
        return Excel::download(new SiswaExport, 'data-siswa.xlsx');
    }

    public function import(Request $req)
    {
        set_time_limit(300);

        $req->validate([
            'file' => 'required|max:10000|mimes:xlsx,xls'
        ]);

        Excel::import(new SiswaImport, $req->file('file'));

        $notificaton = array(
            'message' => 'Data Siswa berhasil di import!',
            'alert-type' => 'success'
        );

        return redirect()->route('siswa.index')->with($notificaton);
    }
}
