<?php

//redirect ke folder
namespace App\Http\Controllers\Admin\Perpus;

use App\Http\Controllers\Controller;
use App\Jobs\ImportDataJob;
use Illuminate\Http\Request;

use Maatwebsite\Excel\Facades\Excel;

use App\Models\Perpus\SekolahModel;
use App\Models\Perpus\JurusanModel;
use App\Models\Perpus\KelasModel;
use App\Models\Perpus\KelasKodeModel;
use App\Models\Stakeholder\SekolahWaliModel;
use App\Models\Stakeholder\GuruModel;
use App\Models\Master\PekerjaanModel;
use App\Models\Stakeholder\KonselorModel;
use App\Models\Master\TempatModel;
use App\Models\Master\PeriodeModel;
use App\Models\Master\AgamaModel;
use App\Models\Siswa\OrtuModel;
use App\Models\Siswa\SiswaModel;
use App\Models\Siswa\SiswaMutasiModel;
use App\Models\Import\ImportexcelSiswaModel;

class KelasKodeController extends Controller
{
    private $views      = 'admin/perpus/kelasKode';
    private $viewsDapodik = 'admin/perpus/kelasKodeDapodik';
    private $url        = 'admin/master/sekolah/indeks-kelas';
    private $title      = 'Halaman Data Indeks Kelas';

    public function __construct()
    {
        createLogActivity();
        // Di isi Construct. Biasanya saya isi untuk Model

        $this->mPerpusSekolah         = new SekolahModel();
        $this->mPerpusJurusan         = new JurusanModel();
        $this->mPerpusKelas         = new KelasModel();
        $this->mPerpusKelasKode         = new KelasKodeModel();
        $this->mSekolahWali         = new SekolahWaliModel();
        $this->mGuru                    = new GuruModel();
        $this->mPeriode             = new PeriodeModel();
        $this->mAgama               = new AgamaModel();
        $this->mPekerjaan           = new PekerjaanModel();
        $this->mKonselor            = new KonselorModel();
        $this->mTempat              = new TempatModel();
        $this->mOrtu                = new OrtuModel();
        $this->mSiswa               = new SiswaModel();
        $this->mSiswaMutasi         = new SiswaMutasiModel();
        $this->mExcelSiswa          = new ImportexcelSiswaModel();
    }

    public function index()
    {
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Indeks Kelas',
        ];

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

    public function create()
    {
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Tambah Data Indeks Kelas',
        ];

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

    public function store(Request $request)
    {

        if (session()->get('role') == 1) {
            $dataPerpusKelasKode = [
                'idPSekolah'    => $request->idPSekolah,
                'idPJurusan'    => $request->idPJurusan,
                'idPKelas'      => $request->idPKelas,
                'nama'          => $request->nama,
            ];
            $this->mPerpusKelasKode->create($dataPerpusKelasKode);
        } else if (session()->get('role') == 2) {
            $jurusan = $this->mPerpusKelas->where('id', $request->idPKelas)->first('idPJurusan');
            $dataPerpusKelasKode = [
                'idPSekolah'    => session()->get('idPSekolah'),
                'idPJurusan'    => $jurusan->idPJurusan,
                'idPKelas'      => $request->idPKelas,
                'nama'          => $request->nama,
            ];
            $this->mPerpusKelasKode->create($dataPerpusKelasKode);
        }

        return redirect("$this->url")->with('sukses', 'Indeks Kelas berhasil di tambahkan');
    }

    public function show($id)
    {
        if (session()->get('role') == 1) {
            $perpus_kelasKode   = $this->mPerpusKelasKode->where('id', $id)->first();
        } else if (session()->get('role') == 2) {
            $perpus_kelasKode   = $this->mPerpusKelasKode->where('id', $id)->where('idPSekolah', session()->get('idPSekolah'))->first();
        }

        if (!$perpus_kelasKode) {
            abort(404);
        }

        $data = [
            'title'             => $this->title,
            'url'               => $this->url,
            'page'              => 'Detail Data Indeks Kelas',
            'id'                => $id,
            'perpus_kelasKode'  => $perpus_kelasKode,
        ];
        return view($this->views . "/show", $data);
    }

    public function edit($id)
    {
        if (session()->get('role') == 1) {
            $perpus_kelasKode      = $this->mPerpusKelasKode->where('id', $id)->first();
        } else if (session()->get('role') == 2) {
            $perpus_kelasKode      = $this->mPerpusKelasKode->where('id', $id)->where('idPSekolah', session()->get('idPSekolah'))->first();
        }

        $data = [
            'title'             => $this->title,
            'url'               => $this->url,
            'page'              => 'Tambah Data Indeks Kelas',
            'id'                => $id,
            'perpus_kelasKode'  => $perpus_kelasKode,
        ];
        return view($this->views . "/edit", $data);
    }

    public function update(Request $request, $id)
    {
        // Validasi
        $request->validate([
            'nama'       => 'required',
        ]);

        $this->mPerpusKelasKode->where('id', $request->id)->update(['nama' => $request->nama]);

        // Response
        return redirect("$this->url")->with('sukses', 'Data Indeks Kelas berhasil di edit');
    }

    public function showDapodik($id)
    {
        if (session()->get('role') == 1) {
            $perpus_kelasKode   = $this->mPerpusKelasKode->where('id', $id)->first();
        } else if (session()->get('role') == 2) {
            $perpus_kelasKode   = $this->mPerpusKelasKode->where('id', $id)->where('idPSekolah', session()->get('idPSekolah'))->first();
        }

        if (!$perpus_kelasKode) {
            abort(404);
        }

        $data = [
            'title'             => $this->title,
            'url'               => $this->url,
            'page'              => 'Detail Data Indeks Kelas',
            'id'                => $id,
            'perpus_kelasKode'  => $perpus_kelasKode,
        ];
        return view($this->viewsDapodik . "/show", $data);
    }

    public function editDapodik($id)
    {
        if (session()->get('role') == 1) {
            $perpus_kelasKode      = $this->mPerpusKelasKode->where('id', $id)->first();
        } else if (session()->get('role') == 2) {
            $perpus_kelasKode      = $this->mPerpusKelasKode->where('id', $id)->where('idPSekolah', session()->get('idPSekolah'))->first();
        }

        $data = [
            'title'             => $this->title,
            'url'               => $this->url,
            'page'              => 'Tambah Data Indeks Kelas',
            'id'                => $id,
            'perpus_kelasKode'  => $perpus_kelasKode,
        ];
        return view($this->viewsDapodik . "/edit", $data);
    }

    public function import(Request $request)
    {
        // validasi
        $validateData = $request->validate([
            'file_excel'                    => 'required|mimes:csv,xls,xlsx'
        ], [
            'file_excel.required'           => 'Pilih file terlebih dahulu',
            'file_excel.mimes'              => 'Format data harus csv, xls atau xlsx',
        ]);

        // Library Import Excel
        $file = $validateData['file_excel'];
        $collection = Excel::toCollection(collect([]), $file); // ke convert collection

        $bisa = 0;
        $ada = 0;

        foreach ($collection[0] as $row) {
            // skip header

            $i = 0;
            if ($i <> 1) {

                try {
                    if ($row[0] == 'nisn')
                        continue;

                    $cekSiswa = $this->mSiswa->where('nisn', $row[0])->where('idMStatus', 1)->first();
                    if (isset($cekSiswa)) {
                        $ada++;
                        continue;
                    }

                    if ($row[0] == null || $row[1] == null || $row[2] == null || $row[3] == null || $row[4] == null || $row[5] == null || $row[6] == null) {
                        $ada++;
                        continue;
                    }

                    // ambil dari excel
                    $idPKKode           = $request->kelasKode;
                    // $idMAgama           = desc($row[0]);
                    $idMStatus          = 1; //Langsung aktif
                    // $idSKonselor        = desc($row[1]);
                    $nisn               = $row[0];
                    $nama               = $row[1];
                    $lahir_tanggal      = $row[2];
                    $lahir_tempat       = $row[3];
                    $telp               = $row[4];

                    $idPPKelas          = 1; // Langsung Sesuai Periode Sekarang
                    $idPPStatus         = 1; // Langsung Sesuai Periode Sekarang
                    // $idMTempat          = desc($row[6]);


                    $dataSiswa = [
                        'idPSekolah'        => session()->get('idPSekolah'),
                        'idPKKode'          => $idPKKode,
                        'idMAgama'          => 0,
                        'idPPeriode'        => session()->get('idPPeriode') ?? '',
                        'idMStatus'         => $idMStatus,
                        'idSKonselor'       => 0,
                        'nisn'              => $nisn,
                        'nama'              => $nama,
                        'lahir_tanggal'     => $lahir_tanggal,
                        'lahir_tempat'      => $lahir_tempat,
                        'telp'              => $telp,
                        'idPPKelas'         => $idPPKelas,
                        'idPPStatus'        => $idPPStatus,
                        'idMTempat'         => 0,
                    ];
                    // echo json_encode($dataSiswa);
                    // dd($dataSiswa);
                    $siswa = $this->mSiswa->create($dataSiswa);

                    // tambah mutasi
                    $dataSiswaMutasi = [
                        'idSiswa'       => $siswa['id'],
                        'idPKKode'      => $idPKKode,
                        'idPPeriode'    => session()->get('idPPeriode') ?? '',
                        'idMStatus'     => $idMStatus,
                    ];
                    $this->mSiswaMutasi->create($dataSiswaMutasi);

                    $namaOrtu           = $row[5];
                    $alamatOrtu         = $row[6];
                    // $idMPekerjaan       = desc($row[9]);

                    $dataOrtu = [
                        'idPSekolah'    => session()->get('idPSekolah'),
                        'idSiswa'       => $siswa['id'],
                        'idMPekerjaan'  => 0,
                        'nama'          => $namaOrtu,
                        'alamat'        => $alamatOrtu,
                    ];
                    // echo json_encode($dataOrtu);
                    $this->mOrtu->create($dataOrtu);

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

        $recordImport = [
            'idUser'        => session()->get('users_id'),
            'idPSekolah'    => session()->get('idPSekolah'),
            'idPPeriode'    => session()->get('idPPeriode'),
        ];
        $this->mExcelSiswa->create($recordImport);

        return redirect("$this->url")->with('sukses', 'Data Siswa di Kelas berhasil di import. masuk: ' . $bisa . ', gagal: ' . $ada . ' (karena sudah ada siswa tsb / data ada yang kosong)');
    }

    public function importDapodik(Request $request)
    {
        // validasi
        $validateData = $request->validate([
            'file_excel'                    => 'required|mimes:csv,xls,xlsx'
        ], [
            'file_excel.required'           => 'Pilih file terlebih dahulu',
            'file_excel.mimes'              => 'Format data harus csv, xls atau xlsx',
        ]);

        $fileSave = $request->file('file_excel')->store('imports');
        $filePath = storage_path('app/' . $fileSave);
        $dataJob = [];
        $dataJob['jenis']       = 'importSiswa';
        $dataJob['file_path']   = $filePath;

        // Setting Siswa
        $idPKKode           = $request->kelasKode;
        $idMStatus          = 1; //Langsung aktif
        $idPPKelas          = 1; // Langsung Sesuai Periode Sekarang
        $idPPStatus         = 1; // Langsung Sesuai Periode Sekarang

        $dataJob['idUser']        = session()->get('users_id');
        $dataJob['idPSekolah']    = session()->get('idPSekolah');
        $dataJob['idPPeriode']    = session()->get('idPPeriode');
        $dataJob['idPKKode']      = $idPKKode;
        $dataJob['idMStatus']     = $idMStatus;
        $dataJob['idPPKelas']     = $idPPKelas;
        $dataJob['idPPStatus']    = $idPPStatus;

        ImportDataJob::dispatch($dataJob);
    }

    public function delete($id)
    {
        try {
            if (session()->get('role') == 1) {
                $this->mPerpusKelasKode->where('id', $id)->delete();
            } else if (session()->get('role') == 2) {
                $this->mPerpusKelasKode->where('id', $id)->where('idPSekolah', session()->get('idPSekolah'))->delete();
            }

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