<?php

namespace App\Http\Controllers\Admin\Import;

use App\Http\Controllers\Controller;
use App\Imports\ImportDapodikGuru;
use App\Jobs\ImportDataJob;
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\ImportDapodik\ImportExcelGuruModel as ImportexcelGuruModel;
use App\Models\ImportDapodik\ImportDapodikGuruModel;
use App\Models\Perpus\KelasKodeModel;
use App\Models\Master\PeriodeModel;
use App\Models\Stakeholder\GuruModel;
use App\Models\Perpus\SekolahModel;
use Illuminate\Support\Facades\DB;

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

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

      public function datatable()
      {
            $data     = $this->mExcelGuru->where('idPSekolah', session()->get('idPSekolah'))->get();
            $formattedData = $data->map(function ($item, $key) {
                  return [
                        'DT_RowIndex' => $key + 1,
                        'periode' => $item->periode->nama_periode,
                        'nip' => $item->nip,
                        'nama' => $item->nama,
                        'created_at' => $item->created_at->format('Y-m-d H:i:s'),
                        'username' => $item->user->username ?? '-',
                        'status' => $item->status
                  ];
            });

            return response()->json([
                  'draw' => intval(request()->get('draw')),
                  'recordsTotal' => $formattedData->count(),
                  'recordsFiltered' => $formattedData->count(),
                  'data' => $formattedData
            ]);
      }

      public function index()
      {
            $excelGuru     = $this->mExcelGuru->where('idPSekolah', session()->get('idPSekolah'))->get();
            $dapodikGuru     = $this->mDapodikGuru->where('idPSekolah', session()->get('idPSekolah'))->get();
            $data = [
                  'title'         => $this->title,
                  'url'           => $this->url,
                  'page'          => 'Data Import Guru',
                  'excelGuru'     => $excelGuru,
                  'dapodikGuru'   => $dapodikGuru
            ];

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

      public function create()
      {
            $data = [
                  'title'         => $this->title,
                  'url'           => $this->url,
                  'page'          => 'Import Excel Guru',
            ];

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

      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',
            ]);

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

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


            ImportDataJob::dispatch($dataJob);

            // Library Import Excel
            // $file = $validateData['file_excel'];
            // Excel::import(new ImportDapodikGuru, $request->file('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; 
            //             $nip                = $nip;
            //             $nama               = $row[1];

            //             $dataGuru = [
            //                   'idPSekolah'        => $idPSekolah,
            //                   'nip'               => $nip,
            //                   'nama'              => $nama,
            //                   'status'            => $status
            //             ];

            //             $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
            //       ];
            //       $this->mExcelGuru->create($recordImport);
            // }

            // $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)';
            $pesan = "Berhasil import";
            return redirect("$this->url")->with('sukses', $pesan);
      }
}
