<?php

namespace App\Http\Controllers\Admin\Layanan\Surat;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Models\Master\PeriodeModel;

use App\Models\Perpus\SekolahModel;
use App\Models\Perpus\KelasKodeModel;

use App\Models\Stakeholder\KepsekModel;
use App\Models\Stakeholder\WakaKesiswaanModel;
use App\Models\Stakeholder\KonselorModel;
use App\Models\Stakeholder\GuruModel;
use App\Models\Stakeholder\SekolahWaliModel;

use App\Models\Siswa\SiswaModel;
use App\Models\Siswa\OrtuModel;

use App\Models\Layanan\Surat\SPMundurModel;

use PhpOffice\PhpWord\TemplateProcessor;

class SPMundurController extends Controller
{
    
    private $views      = 'admin/layanan/surat/sp_mundur';
    private $url        = 'admin/layanan/surat/pernyataan/mundur';
    private $title      = 'Halaman Form Pernyataan Mundur';

public function __construct()
    {
        createLogActivity();
        $this->mPeriode         = New PeriodeModel();

        $this->mPerpusSekolah   = new SekolahModel();
        $this->mKelasKode       = new KelasKodeModel();

        $this->mKepsek          = New KepsekModel();
        $this->mKesiswaan       = New WakaKesiswaanModel();
        $this->mKonselor        = New KonselorModel();
        $this->mGuru            = New GuruModel();
        $this->mSekolahWali     = New SekolahWaliModel();

        $this->mSiswa           = New SiswaModel();
        $this->mOrtu            = New OrtuModel();

        $this->mMundur          = New SPMundurModel();
    }

    public function index()
    {
        $wherenyaa = [
            'idPSekolah'    => session()->get('idPSekolah'),
            'idSKonselor'   => session()->get('idSKonselor'),
        ];
        $mundur = $this->mMundur->where($wherenyaa)->get();

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Surat Pernyataan Mundur',
            'mundur'        => $mundur
        ];
        return view($this->views . "/index", $data);
    }

    public function create()
    {
        // $kepsek = $this->mKepsek->where('idPSekolah', session()->get('idPSekolah'))->get();
        // $konselor = $this->mKonselor->get();
        // $periode = $this->mPeriode->get();
        // $kesiswaan = $this->mKesiswaan->get();
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Tambah Permintaan Surat Pernyataan Mundur',
            // 'kepsek'        => $kepsek,
            // 'konselor'      => $konselor,
            // 'periode'       => $periode,
            // 'kesiswaan'     => $kesiswaan
        ];
        return view($this->views . "/create", $data);
    }

    public function store(Request $request)
    {
        $siswa = $this->mSiswa->where('id', $request->idSiswa)->first();
        $ortu = $this->mOrtu->where('idSiswa', $siswa['id'])->first();
        if(!isset($ortu)){
            return redirect("$this->url")->with('gagal', 'Data Ortu tidak ditemukan');
        };

        $kelaskode = $this->mKelasKode->where('id', $request->idPKKode)->first();
        $wali = $this->mSekolahWali->where('id', $kelaskode['idSWali'])->first();
        if(!isset($wali)){
            return redirect("$this->url")->with('gagal', 'Wali Kelas belum di set');
        };

        $whereKesiswa = [
            'idPSekolah'    => session()->get('idPSekolah'),
            'status'        => 1
        ];
        $kesiswaan = $this->mKesiswaan->where($whereKesiswa)->first();

        if(!isset($kesiswaan)){

            return redirect("$this->url")->with('gagal', 'Waka Kesiswaan belum di set');
        };

        $whereKep = [
            'idPSekolah'    => session()->get('idPSekolah'),
            'status'        => 1
        ];
        $kepsek = $this->mKepsek->where($whereKep)->first();
        if(!isset($kepsek)){
            return redirect("$this->url")->with('gagal', 'Kepala Sekolah belum di set');
        };

        $siswa = $this->mSiswa->where('id', $request->idSiswa)->first();
        $whereKons = [
            'id'            => $siswa['idSKonselor'],
            'status'        => 1,
        ];
        $konselor   = $this->mKonselor->where($whereKons)->first();
        if(!isset($konselor)){
            return redirect("$this->url")->with('gagal', 'Guru Konseling belum di set atau tidak aktif');
        };

        $suratWaktu = $request->surat_waktu;  
        $suratWaktunew = date("d-m-Y", strtotime($suratWaktu));  
        $dataMundur = [
            'idPSekolah'            => session()->get('idPSekolah'),
            'idSKonselor'           => session()->get('idSKonselor'),
            'idPKKode'              => $request->idPKKode,
            'idPPeriode'            => session()->get('idPPeriode'),
            'idSiswa'               => $request->idSiswa,
            'idSWali'               => $wali['id'],
            'idOrtu'                => $ortu['id'],
            'idSKesiswaan'          => $kesiswaan['id'],
            'idSKonselor'           => $konselor['id'],
            'idSKepsek'             => $kepsek['id'],
            'kode_unik'             => strtoupper(bin2hex(random_bytes(3))),
            'surat_tempat'          => $request->surat_tempat,
            'surat_waktu'           => $suratWaktunew,
        ];
        $this->mMundur->create($dataMundur);
        $mundur = $this->mMundur->where('kode_unik', $dataMundur['kode_unik'])->first();
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Surat Pernyataan Mundur',
            'mundur'        => $mundur,
        ];
        return view($this->views . "/show", $data); 
        
    }

    public function show($id)
    {
        // Get Data
        $mundur = $this->mMundur->where('kode_unik', $id)->first();
        
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Surat Pernyataan Mundur',
            'mundur'    => $mundur,
        ];
        return view($this->views . "/show", $data);
    }

    public function download($id)
    {
        if (!cekKopSurat(session()->get('idPSekolah'))) {
            return redirect("admin/dashboard")->with('gagal', 'Kop Surat tidak ditemukan, mohon upload ulang melalui login Admin Sekolah');
        }
        $sekolah = $this->mPerpusSekolah->where('id', session()->get('idPSekolah'))->first();
        $mundur = $this->mMundur->where('kode_unik', $id)->first();
        // dd($mundur);
        $datamundur = [
            'namaSekolah'       => $sekolah->nama,
            'KopSurat'          => $sekolah->logo,
            'idSiswa'           => $mundur->siswa->nama,
            'idPKKode'          => $mundur->kelaskode->kelas->nama.' '.$mundur->kelaskode->kelas->jurusan->nama.' '.$mundur->kelaskode->nama,
            'nisn'              => $mundur->siswa->nisn,
            'idOrtu'            => $mundur->ortu->nama,
            'alamatOrtu'        => $mundur->ortu->alamat,
            'pekerjaan'         => $mundur->ortu->pekerjaan->nama,
            'surat_tempat'      => $mundur->surat_tempat,
            'surat_waktu'       => $mundur->surat_waktu, 
            'idSWali'           => $mundur->wali->guru->nama ?? 'Wali belum di SET',
            'nipWali'           => $mundur->wali->guru->nip ?? 'Wali belum di SET',
            'idSKonselor'       => $mundur->konselor->guru->nama ?? 'Guru Konseling belum di SET',
            'nipKonselor'       => $mundur->konselor->guru->nip ?? 'Guru Konseling belum di SET',
            'idSKesiswaan'      => $mundur->kesiswaan->guru->nama ?? 'Kesiswaan belum di SET',
            'nipKesiswaan'      => $mundur->kesiswaan->guru->nip ?? 'Kesiswaan belum di SET',
            'idSKepsek'         => $mundur->kepsek->guru->nama ?? 'Kepsek belum di SET',
            'nipKepsek'         => $mundur->kepsek->guru->nip ?? 'Kepsek belum di SET',
        ];
        // pakai dari sini. sambil buka word coba.docx
        $templateProcessor = new TemplateProcessor('word-template/surat/surat_pernyataan_mundur.docx'); // load template word
        $templateProcessor->setImageValue('KopSurat', array('path' => "upload/logo_sekolah/".$datamundur['KopSurat'], 'width' => 500, 'height' => 200, 'ratio' => true));
        $templateProcessor->setValue('namaSekolah', $datamundur['namaSekolah']); 
        $templateProcessor->setValue('namaSiswa', $datamundur['idSiswa']); 
        $templateProcessor->setValue('kelasSiswa', $datamundur['idPKKode']); 
        $templateProcessor->setValue('nisn', $datamundur['nisn']); 
        $templateProcessor->setValue('namaOrtu', $datamundur['idOrtu']); 
        $templateProcessor->setValue('alamatOrtu', $datamundur['alamatOrtu']); 
        $templateProcessor->setValue('pekerjaan', $datamundur['pekerjaan']); 
        $templateProcessor->setValue('surat_tempat', $datamundur['surat_tempat']); 
        $templateProcessor->setValue('tanggalSurat', $datamundur['surat_waktu']);
        $templateProcessor->setValue('namaWaliKelas', $datamundur['idSWali']);
        $templateProcessor->setValue('nipWaliKelas', $datamundur['nipWali']); 
        $templateProcessor->setValue('namaKonselor', $datamundur['idSKonselor']);
        $templateProcessor->setValue('nipKonselor', $datamundur['nipKonselor']); 
        $templateProcessor->setValue('namaKonselor', $datamundur['idSKonselor']);
        $templateProcessor->setValue('nipKonselor', $datamundur['nipKonselor']); 
        $templateProcessor->setValue('namaWakaKesiswaan', $datamundur['idSKesiswaan']);
        $templateProcessor->setValue('nipWakaKesiswaan', $datamundur['nipKesiswaan']); 
        $templateProcessor->setValue('namaKepsek', $datamundur['idSKepsek']);
        $templateProcessor->setValue('nipKepsek', $datamundur['nipKepsek']); 
        $fileName = 'Surat Siswa mundur'; // nama filenya
        

        // biar bisa dunlud
        $templateProcessor->saveAs('tempor/' . $fileName . '.docx');
        return response()->download('tempor/' . $fileName . '.docx')->deleteFileAfterSend(true);
        // dd($datamundur); 
    }

    public function edit($id){
        $mundur = $this->mMundur->where('kode_unik', $id)->first();
        
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Surat Keterangan Mundur',
            'mundur'     => $mundur,
        ];

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

    }

    public function update(Request $request, $id)
    {
        $dataUbah = $this->mMundur->where('kode_unik', $id)->first();

        if (isset($request->surat_waktu)) {
            $suratWaktu     = $request->surat_waktu;
            $suratWaktunew  = date("d-m-Y", strtotime($suratWaktu));
        } else {
            $suratWaktunew     = $dataUbah->surat_waktu;  
        }

        $dataMundur = [
            // 'idPSekolah'            => session()->get('idPSekolah'),
            // 'idSKonselor'           => session()->get('idSKonselor'),
            // 'idPKKode'              => $request->idPKKode,
            // 'idPPeriode'            => session()->get('idPPeriode'),
            // 'idSiswa'               => $request->idSiswa,
            // 'idSWali'               => $wali['id'],
            // 'idOrtu'                => $ortu['id'],
            // 'idSKesiswaan'          => $kesiswaan['id'],
            // 'idSKonselor'           => $konselor['id'],
            // 'idSKepsek'             => $kepsek['id'],
            // 'kode_unik'             => strtoupper(bin2hex(random_bytes(3))),
            'surat_tempat'          => $request->surat_tempat,
            'surat_waktu'           => $suratWaktunew,
        ];
        
        $this->mMundur->where('kode_unik', $id)->update($dataMundur);

        return redirect("$this->url")->with('sukses', 'Data Surat Keterangan Mundur untuk '.$dataUbah->siswa->nama.' berhasil di edit');
    }

    public function destroy($id)
    {
        $this->mMundur->where('kode_unik', $id)->delete();

        return redirect("$this->url")->with('sukses', 'Data Surat Keterangan Mundur berhasil di hapus');
    }
}
