<?php

namespace App\Http\Controllers\Admin\Import;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;


// use App\Imports\LulusanImport;
// use App\Exports\LulusanExport;
use Maatwebsite\Excel\Facades\Excel;

// Panggil Nama file Model yang mau dipake
use App\Models\Import\ImportexcelGuruModel as ImportexcelGuruModel;

use App\Models\Perpus\KelasKodeModel;
use App\Models\Master\PeriodeModel;
use App\Models\Stakeholder\GuruModel;
use App\Models\Perpus\SekolahModel;

class ImportGuruController extends Controller
{
    private $views      = 'admin/import/importGuru';
    private $url        = 'admin/import/guru';
    private $title      = 'Halaman Import Guru';

public function __construct()
    {
        createLogActivity();
        // Di isi Construct
        $this->mExcelGuru           = new ImportexcelGuruModel();
        $this->mGuru                = New GuruModel();
        $this->mPeriode             = new PeriodeModel();
        $this->mPerpusSekolah         = new SekolahModel();
    }

    public function index()
    {
        $excelGuru     = $this->mExcelGuru->where('idPSekolah', session()->get('idPSekolah'))->get();

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Import Guru',
            'excelGuru'     => $excelGuru,
        ];

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

    public function create()
    {

        // echo json_encode($konselor); die;
        // dd(session()->all());

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Import Excel Guru',
        ];

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


        // $encrypted = Crypt::encryptString('12');
		// $decrypted = Crypt::decryptString($encrypted);
 
		// echo "Hasil Enkripsi : " . $encrypted;
		// echo "<br/>";
		// echo "<br/>";
		// echo "Hasil Dekripsi : " . $decrypted;
    }

    public function store(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

        $seenNips = [];
        $bisa=0;
        $ada=0;
        $nipMasuk = [];
        $nipGagal = [];

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

            $i=0;
            if($i <> 1) {
            
                if ($row[0] == 'nip')
                    continue;

                $nip = (string)$row[0];

                $cekGuru = $this->mGuru->where('nip', $nip)->first();
                if(isset($cekGuru)){
                    $ada++;
                    continue;
                }

                if(!is_numeric($nip) || $nip == null || $row[1] == null || strlen($nip) < 10){
                    $ada++;
                    $nipGagal[] = [
                        'nip'       => $nip, 
                        'nama'      => $row[1],
                        'reason'    => "Bukan numeric, data kosong atau nip kurang dari 10"
                    ];
                    continue;
                }

                if (isset($seenNips[$nip])) {
                    $ada++;
                    $nipGagal[] = [
                        'nip'       => $nip, 
                        'nama'      => $row[1],
                        'reason'    => "NIP sudah terdaftar"
                    ];
                    continue; // Jika NIP sudah ada, lewati iterasi ini
                }
                $seenNips[$nip] = true; // tandai kalo sudah ada

                // ambil dari excel
                $idPSekolah         = session()->get('idPSekolah');
                $status             = 1; //Langsung aktif
                $nip                = $nip;
                $nama               = $row[1];
                // $mapel              = $row[2];
             
                $dataGuru = [
                    'idPSekolah'        => $idPSekolah,
                    'nip'               => $nip,
                    'nama'              => $nama,
                    'status'            => $status,
                    // 'mapel'             => $mapel,
                ];
                // echo json_encode($dataSiswa);
                // dd($dataSiswa);
                $guru = $this->mGuru->create($dataGuru);
                $nipMasuk[] = ['nip' => $nip, 'nama' => $nama, 'reason' => "masuk"];
                $bisa++;
            }
            $i++;

            $recordImport = [
                'idUser'        => session()->get('users_id'),
                'idPSekolah'    => session()->get('idPSekolah'),
                'idPPeriode'    => session()->get('idPPeriode'),
                'nip'           => $nip,
                'nama'          => $nama,
                // 'mapel'         => $mapel,
            ];
            $this->mExcelGuru->create($recordImport);
        }
        
        // return redirect("$this->url")->with('sukses', 'Data Guru di Kelas berhasil di import. masuk: '.$bisa.', gagal: '.$ada.' (karena sudah ada guru tsb / data ada yang kosong / nip dibawah 18 karakter / nip duplikasi)');
        $pesan = 'Data Guru di Kelas berhasil di import. masuk: ' . $bisa . ', gagal: ' . $ada . ' (karena sudah ada guru tsb / data ada yang kosong / nip dibawah 10 karakter / nip duplikasi / nip bukan angka)';

        // Menambahkan pesan untuk nip yang masuk dan gagal
        // $pesan .= "\n\nNIP yang masuk:\n";
        // foreach ($nipMasuk as $data) {
        //     $pesan .= $data['nip'] . ' - ' . $data['nama']. "\n";
        // }

        // $pesan .= "\nNIP yang gagal:\n";
        // foreach ($nipGagal as $data) {
        //     $pesan .= $data['nip'] . ' - ' . $data['nama'] . ' - ' . $data['reason'] . "\n";
        // }

        return redirect("$this->url")->with('sukses', $pesan);
    }
}
