<?php

namespace App\Http\Controllers\Admin\Stakeholder;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

// Library
use DB;
use Illuminate\Support\Facades\Hash;

use App\Models\User\UserModel;
use App\Models\Perpus\SekolahModel;
use App\Models\Stakeholder\KonselorModel;
use App\Models\Stakeholder\GuruModel;
use App\Models\Siswa\SiswaModel;

class KonselorController extends Controller
{
    private $views      = 'admin/stakeholder/konselor';
    private $url        = 'admin/guru/konselor';
    private $title      = 'Halaman Konselor';

public function __construct()
    {
        createLogActivity();
        $this->mUser            = new UserModel();
        $this->mPerpusSekolah   = new SekolahModel();
        $this->mKonselor        = new KonselorModel();
        $this->mGuru            = new GuruModel();
        $this->mSiswa           = new SiswaModel();
    
    }

    public function index()
    {
        $konselors = DB::table('sekolah_konselor as k')
        ->join('sekolah_guru as g', 'g.id', '=', 'k.idSGuru')
        ->leftJoin('perpus_kelasKode as kk', function ($join) {
            $join->whereRaw('FIND_IN_SET(kk.id, k.kelas)');
        })
        ->leftJoin('perpus_kelas as pk', 'kk.idPKelas', '=', 'pk.id')
        ->leftJoin('perpus_jurusan as pj', 'kk.idPJurusan', '=', 'pj.id')
        ->select(
            'k.id', 
            'g.nama as guru', 
            'g.nip',
            'k.status',
            DB::raw('GROUP_CONCAT(CONCAT(pk.nama, " ", pj.nama, " ", kk.nama) SEPARATOR ", ") as kelas')
        )
        ->where('k.idPSekolah', session()->get('idPSekolah'))
        ->groupBy('k.id', 'g.nama', 'g.nip')
        ->get();

        // echo json_encode($konselors); die;

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Konselor',
            'konselor'      => $konselors,
        ];

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

    public function create()
    {
        $konselor = $this->mKonselor->where('idPSekolah', session()->get('idPSekolah'))->pluck('idSGuru')->toArray();
        $guru = $this->mGuru->whereNotIn('id', $konselor)
                            ->where('idPSekolah', session()->get('idPSekolah'))->get();
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Tambah Data Konselor',
            'guru'          => $guru,
        ];

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

    public function store(Request $request)
    {
        $dataKonselor = [
            'idPSekolah'    => session()->get('idPSekolah'),
            'idSGuru'       => $request->idSGuru,
            'status'        => 1
        ];
        $konselor = $this->mKonselor->create($dataKonselor);

        // add new user konselor
        $guru = $this->mGuru->where('idPSekolah', session()->get('idPSekolah'))->where('id', $request->idSGuru)->first();

        $dataUser = [
            'username'          => $guru->nip,
            'password'          => Hash::make("bkpeduli"),
            'sandi'             => "bkpeduli",
            'status'            => $request->status,
            'idPSekolah'        => session()->get('idPSekolah'),
            'role'              => 3,
            'status'            => 1,
            'idPPeriode'        => session()->get('idPPeriode'),
            'idSKonselor'       => $konselor->id
        ];
        $this->mUser->create($dataUser);

        // dd($kepsek);
        return redirect("$this->url")->with('sukses', 'Konselor Berhasil di Ditambah dengan akun Username: '.$guru->nip.' Password: bkpeduli , Mohon segera ganti password anda setelah login');
    }

    public function show($id)
    {
        $konselor = $this->mKonselor->where('id', $id)->first();
        $guru = $this->mGuru->where('id', $id)->first();
        $siswa = $this->mSiswa->where('idSKonselor', $id)->get();


        // if (!$guru || !$konselor || !$siswa) {
        //     return redirect()->back()->with('gagal', 'Data tidak ditemukan atau sudah dihapus.');
        // }

        $data = [
            'title'                 => $this->title,
            'url'                   => $this->url,
            'page'                  => 'Detail Data Konselor',
            'id'                    => $id,
            'konselor'              => $konselor,
            'guru'                  => $guru,
            'siswa'                 => $siswa,
            
        ];
        return view($this->views . "/show", $data);
    }

    public function edit($id)
    {
        $konselor = $this->mKonselor->where('id', $id)->first();
        $guru = $this->mGuru->where('idPSekolah', session()->get('idPSekolah'))->where('id', $konselor->idSGuru)->first();
        
        // echo json_encode($gurupiket); die;
        if($konselor['status'] == 1){
            $data =  [
                'status' => 0
            ];
            $this->mKonselor->where('id', $id)->update($data);
        }elseif($konselor['status'] == 0){
            $data =  [
                'status' => 1
            ];
            $this->mKonselor->where('id', $id)->update($data);
        }
        $this->mUser->where('idPSekolah', session()->get('idPSekolah'))->where('username', $guru->nip)->update($data);

        return redirect("$this->url")->with('sukses', 'Data Guru Konselor berhasil di ganti statusnya');
    }

    public function settingMassal()
    {
        $konselor = $this->mKonselor->where('idPSekolah', session()->get('idPSekolah'))->get();

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Setting Massal Konselor',
            'konselor'      => $konselor,
        ];

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

    public function settingMassalProcess(Request $request)
    {
        try {
            $kelas = implode(',', $request->idPKKode);
            // $kelas = json_encode($kelas); 
            // echo $kelas; die;
            $this->mKonselor->where('id', $request->idSKonselor)->update(['kelas' => $kelas]);

            $this->mSiswa
                ->where('idPSekolah', session()->get('idPSekolah'))
                ->whereIn('idPKKode', $request->idPKKode)
                ->update(['idSKonselor' => $request->idSKonselor]);

            return redirect("$this->url")->with('sukses', 'Berhasil ! Setting Massal Konselor berhasil');

        } catch (\Exception $e) {
            DB::rollback();
            // error message
            return redirect("$this->url")->with('gagal', 'Terjadi error: '. $e->getMessage());
        }
    }
}
