<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BankSoalIkkAdminController extends Controller
{
    public function index(Request $request)
    {
        $urusan = $request->get('urusan');
        $status = $request->get('status');

        $query = DB::table('bank_soal_sikk')
            ->orderBy('kode_ikk', 'asc');

        if ($urusan) {
            $query->where('urusan', $urusan);
        }

        if ($status) {
            $query->where('status', $status);
        }

        $bankSoal = $query->paginate(10);

        // Get unique urusan for filter
        $urusanList = DB::table('bank_soal_sikk')
            ->select('urusan')
            ->distinct()
            ->pluck('urusan');

        return view('admin.ikk.bank_soal.index', compact('bankSoal', 'urusanList', 'urusan', 'status'));
    }

    public function create()
    {
        $opdList = DB::table('opds')
            ->where('is_active', true)
            ->orderBy('name', 'asc')
            ->get();

        return view('admin.ikk.bank_soal.create', compact('opdList'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'kode_ikk' => 'required|string|unique:bank_soal_sikk,kode_ikk|max:20',
            'urusan' => 'required|string|max:100',
            'bidang' => 'required|string|max:100',
            'ikk_output' => 'required|string|max:200',
            'ikk_outcome' => 'required|string',
            'rumus_perhitungan' => 'required|string',
            'satuan' => 'required|string|max:50',
            'sumber_data' => 'required|string|max:200',
            'opd_penanggung_jawab' => 'required|string|max:100',
            'tahun_mulai' => 'required|integer|min:2020|max:' . (date('Y') + 5),
            'status' => 'required|in:Aktif,Tidak Aktif',
            'tipe_input' => 'required|in:text,textarea,radio,select',
            'pilihan_jawaban' => 'required_if:tipe_input,radio,select|nullable|string'
        ]);

        // Parse pilihan jawaban if tipe input is radio or select
        $pilihanJawaban = null;
        if (in_array($request->tipe_input, ['radio', 'select']) && $request->pilihan_jawaban) {
            // Split by newline and create array
            $options = array_filter(array_map('trim', explode("\n", $request->pilihan_jawaban)));
            $pilihanJawaban = json_encode(array_values($options));
        }

        DB::table('bank_soal_sikk')->insert([
            'kode_ikk' => $request->kode_ikk,
            'urusan' => $request->urusan,
            'bidang' => $request->bidang,
            'ikk_output' => $request->ikk_output,
            'ikk_outcome' => $request->ikk_outcome,
            'rumus_perhitungan' => $request->rumus_perhitungan,
            'satuan' => $request->satuan,
            'sumber_data' => $request->sumber_data,
            'opd_penanggung_jawab' => $request->opd_penanggung_jawab,
            'tahun_mulai' => $request->tahun_mulai,
            'status' => $request->status,
            'tipe_input' => $request->tipe_input,
            'pilihan_jawaban' => $pilihanJawaban,
            'created_at' => now(),
            'updated_at' => now()
        ]);

        return redirect()->route('admin.ikk.bank-soal.index')
            ->with('success', 'Bank Soal IKK berhasil ditambahkan');
    }

    public function edit($id)
    {
        $soal = DB::table('bank_soal_sikk')->where('id', $id)->first();

        if (!$soal) {
            return redirect()->route('admin.ikk.bank-soal.index')
                ->with('error', 'Data tidak ditemukan');
        }

        $opdList = DB::table('opds')
            ->where('is_active', true)
            ->orderBy('name', 'asc')
            ->get();

        return view('admin.ikk.bank_soal.edit', compact('soal', 'opdList'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'kode_ikk' => 'required|string|max:20|unique:bank_soal_sikk,kode_ikk,' . $id,
            'urusan' => 'required|string|max:100',
            'bidang' => 'required|string|max:100',
            'ikk_output' => 'required|string|max:200',
            'ikk_outcome' => 'required|string',
            'rumus_perhitungan' => 'required|string',
            'satuan' => 'required|string|max:50',
            'sumber_data' => 'required|string|max:200',
            'opd_penanggung_jawab' => 'required|string|max:100',
            'tahun_mulai' => 'required|integer|min:2020|max:' . (date('Y') + 5),
            'status' => 'required|in:Aktif,Tidak Aktif',
            'tipe_input' => 'required|in:text,textarea,radio,select',
            'pilihan_jawaban' => 'required_if:tipe_input,radio,select|nullable|string'
        ]);

        // Parse pilihan jawaban if tipe input is radio or select
        $pilihanJawaban = null;
        if (in_array($request->tipe_input, ['radio', 'select']) && $request->pilihan_jawaban) {
            // Split by newline and create array
            $options = array_filter(array_map('trim', explode("\n", $request->pilihan_jawaban)));
            $pilihanJawaban = json_encode(array_values($options));
        }

        DB::table('bank_soal_sikk')
            ->where('id', $id)
            ->update([
                'kode_ikk' => $request->kode_ikk,
                'urusan' => $request->urusan,
                'bidang' => $request->bidang,
                'ikk_output' => $request->ikk_output,
                'ikk_outcome' => $request->ikk_outcome,
                'rumus_perhitungan' => $request->rumus_perhitungan,
                'satuan' => $request->satuan,
                'sumber_data' => $request->sumber_data,
                'opd_penanggung_jawab' => $request->opd_penanggung_jawab,
                'tahun_mulai' => $request->tahun_mulai,
                'status' => $request->status,
                'tipe_input' => $request->tipe_input,
                'pilihan_jawaban' => $pilihanJawaban,
                'updated_at' => now()
            ]);

        return redirect()->route('admin.ikk.bank-soal.index')
            ->with('success', 'Bank Soal IKK berhasil diperbarui');
    }

    public function destroy($id)
    {
        // Check if used in lembar jawab or pelaporan
        $usedInLembarJawab = DB::table('lembar_jawab_ikk')
            ->where('bank_soal_id', $id)
            ->exists();

        $usedInPelaporan = DB::table('pelaporan_ikk')
            ->where('bank_soal_id', $id)
            ->exists();

        if ($usedInLembarJawab || $usedInPelaporan) {
            return redirect()->route('admin.ikk.bank-soal.index')
                ->with('error', 'Bank Soal tidak dapat dihapus karena sudah digunakan dalam lembar jawab atau pelaporan');
        }

        DB::table('bank_soal_sikk')->where('id', $id)->delete();

        return redirect()->route('admin.ikk.bank-soal.index')
            ->with('success', 'Bank Soal IKK berhasil dihapus');
    }
}
