<?php

namespace App\Http\Controllers\Operator;

use App\Http\Controllers\Controller;
use App\Models\Auth\Biodata;
use App\Models\User;
use App\Repositories\Auth\IsdmRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use RealRashid\SweetAlert\Facades\Alert;

class SyncNoidentitasController extends Controller
{
    /** @var IsdmRepository */
    private $isdmRepo;

    public function __construct(IsdmRepository $isdmRepo)
    {
        $this->isdmRepo = $isdmRepo;
    }

    /**
     * Daftar dosen yang noidentitas-nya masih null.
     */
    public function index()
    {
        $data['title'] = 'Sync Noidentitas Dosen';
        $data['users'] = User::with(['rBiodata', 'rolesCustom'])
            ->whereHas('rolesCustom', function ($q) {
                return $q->where('name', 'dosen');
            })
            ->whereHas('rBiodata', function ($q) {
                return $q->whereNull('noidentitas');
            })
            ->orderBy('name', 'asc')
            ->get();

        return view('backend.operator.sync_noidentitas.index', $data);
    }

    /**
     * Ambil NIDN/NUPTK dari API i-sdm berdasarkan email (untuk tombol Sync - isi ke kolom input).
     */
    public function fetch(Request $request)
    {
        $biodataId = $request->input('biodata_id');
        if (!$biodataId) {
            return response()->json(['success' => false, 'message' => 'biodata_id wajib.']);
        }

        try {
            $id = Crypt::decrypt($biodataId);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'ID tidak valid.']);
        }

        $user = User::find($id);
        if (!$user || !$user->email) {
            return response()->json(['success' => false, 'message' => 'User/email tidak ditemukan.']);
        }

        $data = $this->isdmRepo->getBiodataByEmail($user->email);
        if (!$data || ($data['nidn_or_nuptk'] ?? '') === '') {
            return response()->json(['success' => false, 'message' => 'Data tidak ditemukan di i-sdm untuk email ini.']);
        }

        return response()->json([
            'success' => true,
            'userid' => $data['userid'] ?? '',
            'nidn' => $data['nidn'] ?? '',
            'nidn_or_nuptk' => $data['nidn_or_nuptk'],
        ]);
    }

    /**
     * Update biodata: simpan noidentitas (NIDN ?? NUPTK) dari API i-sdm ke biodata simpmw.
     */
    public function update(Request $request)
    {
        $request->validate([
            'biodata_id' => 'required|string',
            'identifier' => 'required|string|max:50',
        ], [
            'identifier.required' => 'NIDN atau NUPTK wajib diisi.',
        ]);

        $biodataId = Crypt::decrypt($request->biodata_id);
        $biodata = Biodata::find($biodataId);

        if (!$biodata) {
            Alert::error('Biodata tidak ditemukan.');
            return redirect()->route('operator.sync-noidentitas.index');
        }

        if ($biodata->noidentitas !== null) {
            Alert::info('Noidentitas sudah terisi.');
            return redirect()->route('operator.sync-noidentitas.index');
        }

        $isdm = $this->isdmRepo->getByNidnOrNip($request->identifier);

        if (empty($isdm) || !isset($isdm[0])) {
            $isdm = $this->isdmRepo->getByNidnOrNip($request->nip);

            if (empty($isdm) || !isset($isdm[0])) {
                $isdm = $this->isdmRepo->getByNidnOrNip($request->nidn);
            }
        }

        if (trim($request->identifier) !== trim($isdm[0]->nuptk)) {
            Alert::error('NUPTK yg diinput tidak sesuai dengan NUPTK di i-sdm.');
            return redirect()->route('operator.sync-noidentitas.index');
        }

        if (empty($isdm) || !isset($isdm[0])) {
            Alert::error('Data tidak ditemukan di i-sdm. Pastikan NIDN atau NUPTK atau NIPbenar.');
            return redirect()->route('operator.sync-noidentitas.index');
        }

        $row = $isdm[0];
        $noidentitas = $row->nidn ?? $row->nuptk ?? $row->nip ?? null;

        if ($noidentitas === null || $noidentitas === '') {
            Alert::error('Data i-sdm tidak memiliki NIDN/NUPTK.');
            return redirect()->route('operator.sync-noidentitas.index');
        }

        $biodata->noidentitas = $noidentitas;
        $biodata->save();

        Alert::success('Noidentitas berhasil diupdate: ' . $noidentitas);
        return redirect()->route('operator.sync-noidentitas.index');
    }
}
