<?php

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

use Illuminate\Http\Request;
use PhpOffice\PhpWord\TemplateProcessor;

use App\Models\Master\AgamaModel;

use App\Models\Master\PeriodeModel;

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

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

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

use App\Models\Layanan\Surat\TartibModel;

class SPTataTertibController extends Controller
{
    private $views      = 'admin/layanan/surat/sp_tataTertib';
    private $url        = 'admin/layanan/surat/pernyataan/tartib';
    private $title      = 'Halaman Form Pernyataan Tata Tartib';

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

        $this->mPerpusJurusan   = new JurusanModel();
        $this->mPerpusKelas     = new KelasModel();
        $this->mKelasKode       = new KelasKodeModel();
        $this->mPerpusSekolah   = new SekolahModel();
        
        $this->mKepsek          = New KepsekModel();
        $this->mSekolahWali     = new SekolahWaliModel();
        $this->mKonselor        = New KonselorModel();
        $this->mGuru            = New GuruModel();

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

        $this->mTartib          = New TartibModel();
    }

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

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Surat Pernyataan Tata Tertib',
            'tartib'        => $tartib
        ];
        return view($this->views . "/index", $data);
        // echo json_encode($tartib); die;
    }

    public function create()
    {
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Tambah Permintaan Surat Pernyataan Tata Tertib',
        ];
        return view($this->views . "/create", $data);
    }

    public function store(Request $request)
    {
        // masuk sini hasil form create
        $suratWaktu = $request->surat_waktu;  
        $suratWaktunew = date("d-m-Y", strtotime($suratWaktu));

        $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');
        };

        $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');
        };
        
        $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');
        };

        $dataTartib = [
            'idPSekolah'            => session()->get('idPSekolah'),
            'idSKonselor'           => session()->get('idSKonselor'),
            'idPKKode'              => $request->idPKKode,
            'idPPeriode'            => session()->get('idPPeriode'),
            'idSiswa'               => $request->idSiswa,
            'idSWali'               => $wali['id'],
            'idSKonselor'           => $konselor['id'],
            'idOrtu'                => $ortu['id'],
            'idSKepsek'             => $kepsek['id'],
            'kode_unik'             => strtoupper(bin2hex(random_bytes(3))),
            'surat_tempat'          => $request->surat_tempat,
            'surat_waktu'           => $suratWaktunew,
            'isian_menghadap'       => $request->isian_menghadap,
            'isian_jenisMasalah'    => $request->isian_jenisMasalah,
            'isian_penyelesaian'    => $request->isian_penyelesaian,
        ];
        // dd($dataTartib); die;
        $this->mTartib->create($dataTartib);

        $tartib = $this->mTartib->where('kode_unik', $dataTartib['kode_unik'])->first();

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Surat Tata Tertib',
            'tartib'        => $tartib,
        ];

        return view($this->views . "/show", $data)->with('sukses', 'Surat Tata Tertib berhasil di tambah');
    }

    public function show($id)
    {
        // Get Data
        $tartib = $this->mTartib->where('kode_unik', $id)->first();
        
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Surat Tata Tertib',
            'tartib'        => $tartib,
        ];
        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();
        $tartib = $this->mTartib->where('kode_unik', $id)->first();
        // dd($mundur);
        
        $dataTartib = [
            'namaSekolah'           => $sekolah->namaSekolah,
            'KopSurat'              => $sekolah->logo,
            'idPSekolah'            => $tartib->idPSekolah,
            'idPKKode'              => $tartib->kelaskode->kelas->nama.' '.$tartib->kelaskode->kelas->jurusan->nama.' '.$tartib->kelaskode->nama,
            'idPPeriode'            => $tartib->idPPeriode,
            'idSiswa'               => $tartib->siswa->nama,
            'nisn'                  => $tartib->siswa->nisn,
            'idSWali'               => $tartib->wali->guru->nama ?? 'Wali belum di SET',
            'nipWali'               => $tartib->wali->guru->nip ?? 'Wali belum di SET',
            'idSKonselor'           => $tartib->konselor->guru->nama ?? 'Guru Konseling belum di SET',
            'nipKonselor'           => $tartib->konselor->guru->nip ?? 'Guru Konseling belum di SET',
            'idOrtu'                => $tartib->ortu->nama,
            'alamatOrtu'            => $tartib->ortu->alamat,
            'idSKepsek'             => $tartib->kepsek->guru->nama ?? 'Kepsek belum di SET',
            'nipKepsek'             => $tartib->kepsek->guru->nip ?? 'Kepsek belum di SET',
            'surat_tempat'          => $tartib->surat_tempat,
            'surat_waktu'           => $tartib->surat_waktu,
            'isian_menghadap'       => $tartib->isian_menghadap,
            'isian_jenisMasalah'    => $tartib->isian_jenisMasalah,
            'isian_penyelesaian'    => $tartib->isian_penyelesaian,
        ];
        // pakai dari sini. sambil buka word coba.docx
        $templateProcessor = new TemplateProcessor('word-template/surat/surat_pernyataan_tatatertib.docx'); // load template word
        $templateProcessor->setImageValue('KopSurat', array('path' => "upload/logo_sekolah/".$dataTartib['KopSurat'], 'width' => 500, 'height' => 200, 'ratio' => true));
        $templateProcessor->setValue('namaSekolah', $dataTartib['namaSekolah']); 
        $templateProcessor->setValue('namaSiswa', $dataTartib['idSiswa']); 
        $templateProcessor->setValue('alamatSiswa', $dataTartib['alamatOrtu']);
        $templateProcessor->setValue('kelasSiswa', $dataTartib['idPKKode']); 
        $templateProcessor->setValue('noIndukSiswa', $dataTartib['nisn']); 
        $templateProcessor->setValue('namaOrtu', $dataTartib['idOrtu']); 
        $templateProcessor->setValue('alamatOrtu', $dataTartib['alamatOrtu']); 
        $templateProcessor->setValue('menghadapKe', $dataTartib['isian_menghadap']);
        $templateProcessor->setValue('jenisMasalah', $dataTartib['isian_jenisMasalah']); 
        $templateProcessor->setValue('penyelesaian', $dataTartib['isian_penyelesaian']);
        $templateProcessor->setValue('suratTempat', $dataTartib['surat_tempat']); 
        $templateProcessor->setValue('tanggalSurat', $dataTartib['surat_waktu']);
        $templateProcessor->setValue('namaWaliKelas', $dataTartib['idSWali']);
        $templateProcessor->setValue('nipWaliKelas', $dataTartib['nipWali']); 
        $templateProcessor->setValue('namaKonselor', $dataTartib['idSKonselor']);
        $templateProcessor->setValue('nipKonselor', $dataTartib['nipKonselor']); 
        $templateProcessor->setValue('namaKepsek', $dataTartib['idSKepsek']);
        $templateProcessor->setValue('nipKepsek', $dataTartib['nipKepsek']); 
        $templateProcessor->setValue('sangsi', $dataTartib['isian_penyelesaian']); 
        $fileName = 'Surat Pernyataan Tata Tertib'; // nama filenya
        

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

    public function edit($id){
        $tartib = $this->mTartib->where('kode_unik', $id)->first();
        
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Surat Keterangan Tata Tertib',
            'id'            => $id,
            'tartib'        => $tartib,
        ];

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

    }

    public function update(Request $request, $id)
    {
        $dataUbah = $this->mTartib->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;  
        }

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

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

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

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