<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LembarJawabIkkController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(Request $request)
    {
        $user = auth()->user();
        $opd = $request->get('opd');
        $tahun = $request->get('tahun');

        $query = DB::table('lembar_jawab_ikk')
            ->join('bank_soal_sikk', 'lembar_jawab_ikk.bank_soal_id', '=', 'bank_soal_sikk.id')
            ->select(
                'lembar_jawab_ikk.*',
                'bank_soal_sikk.kode_ikk',
                'bank_soal_sikk.ikk_output'
            )
            ->orderBy('lembar_jawab_ikk.tahun', 'desc')
            ->orderBy('lembar_jawab_ikk.created_at', 'desc');

        // If user is OPD, only show their own data
        if ($user->isOpd()) {
            $query->where('lembar_jawab_ikk.opd', $user->opd);
            $opd = $user->opd; // Override filter
        } else {
            // Admin and Verifikator can filter by OPD
            if ($opd) {
                $query->where('lembar_jawab_ikk.opd', $opd);
            }
        }

        if ($tahun) {
            $query->where('lembar_jawab_ikk.tahun', $tahun);
        }

        $lembarJawab = $query->get();

        // Get unique OPD and years for filter
        $opdList = DB::table('lembar_jawab_ikk')
            ->select('opd')
            ->distinct()
            ->pluck('opd');

        $tahunList = DB::table('lembar_jawab_ikk')
            ->select('tahun')
            ->distinct()
            ->orderBy('tahun', 'desc')
            ->pluck('tahun');

        return view('ikk.lembar-jawab.index', compact('lembarJawab', 'opdList', 'tahunList', 'opd', 'tahun'));
    }

    public function create(Request $request)
    {
        $user = auth()->user();

        // Only OPD users can create lembar jawab
        if (!$user->isOpd()) {
            return redirect()->route('ikk.lembar-jawab.index')
                ->with('error', 'Hanya user OPD yang dapat mengisi lembar jawab');
        }

        $bankSoalId = $request->get('bank_soal_id');
        $tahun = $request->get('tahun', date('Y'));
        $opd = $user->opd; // Get OPD from logged-in user

        // Get all active Bank Soal
        $bankSoalList = DB::table('bank_soal_sikk')
            ->where('status', 'Aktif')
            ->orderBy('kode_ikk', 'asc')
            ->get();

        // If specific bank soal selected, get details
        $bankSoal = null;
        if ($bankSoalId) {
            $bankSoal = DB::table('bank_soal_sikk')
                ->where('id', $bankSoalId)
                ->first();
        }

        return view('ikk.lembar-jawab.create', compact('bankSoalList', 'bankSoal', 'tahun', 'opd'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'bank_soal_id' => 'required|integer|exists:bank_soal_sikk,id',
            'opd' => 'required|string|max:100',
            'tahun' => 'required|integer|min:2020',
            'capaian' => 'required|numeric',
            'kendala' => 'nullable|string',
            'tindak_lanjut' => 'nullable|string',
            'file_bukti' => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120',
            'action' => 'required|in:draft,ajukan'
        ]);

        $status = $request->action == 'draft' ? 'DRAFT' : 'DIAJUKAN';

        // Handle file upload
        $fileName = null;
        if ($request->hasFile('file_bukti')) {
            $file = $request->file('file_bukti');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/ikk'), $fileName);
        }

        DB::table('lembar_jawab_ikk')->insert([
            'bank_soal_id' => $request->bank_soal_id,
            'opd' => $request->opd,
            'tahun' => $request->tahun,
            'capaian' => $request->capaian,
            'kendala' => $request->kendala,
            'tindak_lanjut' => $request->tindak_lanjut,
            'file_bukti' => $fileName,
            'status' => $status,
            'created_at' => now(),
            'updated_at' => now()
        ]);

        session()->flash('success', 'Lembar jawab berhasil disimpan dengan status ' . $status);
        return redirect()->route('ikk.lembar-jawab.index');
    }

    public function edit($id)
    {
        $user = auth()->user();

        $lembarJawab = DB::table('lembar_jawab_ikk')
            ->join('bank_soal_sikk', 'lembar_jawab_ikk.bank_soal_id', '=', 'bank_soal_sikk.id')
            ->select(
                'lembar_jawab_ikk.*',
                'bank_soal_sikk.kode_ikk',
                'bank_soal_sikk.ikk_output',
                'bank_soal_sikk.ikk_outcome',
                'bank_soal_sikk.rumus_perhitungan',
                'bank_soal_sikk.satuan',
                'bank_soal_sikk.tipe_input',
                'bank_soal_sikk.pilihan_jawaban'
            )
            ->where('lembar_jawab_ikk.id', $id)
            ->first();

        if (!$lembarJawab) {
            return redirect()->route('ikk.lembar-jawab.index')
                ->with('error', 'Data tidak ditemukan');
        }

        // OPD can only edit their own data with DRAFT status
        if ($user->isOpd()) {
            if ($lembarJawab->opd !== $user->opd) {
                return redirect()->route('ikk.lembar-jawab.index')
                    ->with('error', 'Anda tidak memiliki akses untuk mengedit data ini');
            }
            if ($lembarJawab->status !== 'DRAFT') {
                return redirect()->route('ikk.lembar-jawab.index')
                    ->with('error', 'Hanya lembar jawab dengan status DRAFT yang dapat diedit');
            }
        }

        return view('ikk.lembar-jawab.edit', compact('lembarJawab'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'capaian' => 'required|numeric',
            'kendala' => 'nullable|string',
            'tindak_lanjut' => 'nullable|string',
            'file_bukti' => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120',
            'action' => 'required|in:draft,ajukan'
        ]);

        $status = $request->action == 'draft' ? 'DRAFT' : 'DIAJUKAN';

        $updateData = [
            'capaian' => $request->capaian,
            'kendala' => $request->kendala,
            'tindak_lanjut' => $request->tindak_lanjut,
            'status' => $status,
            'updated_at' => now()
        ];

        // Handle file upload
        if ($request->hasFile('file_bukti')) {
            $file = $request->file('file_bukti');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/ikk'), $fileName);
            $updateData['file_bukti'] = $fileName;
        }

        DB::table('lembar_jawab_ikk')
            ->where('id', $id)
            ->update($updateData);

        session()->flash('success', 'Lembar jawab berhasil diperbarui dengan status ' . $status);
        return redirect()->route('ikk.lembar-jawab.index');
    }

    public function show($id)
    {
        $lembarJawab = DB::table('lembar_jawab_ikk')
            ->join('bank_soal_sikk', 'lembar_jawab_ikk.bank_soal_id', '=', 'bank_soal_sikk.id')
            ->select(
                'lembar_jawab_ikk.*',
                'bank_soal_sikk.kode_ikk',
                'bank_soal_sikk.ikk_output',
                'bank_soal_sikk.ikk_outcome',
                'bank_soal_sikk.rumus_perhitungan',
                'bank_soal_sikk.satuan',
                'bank_soal_sikk.tipe_input',
                'bank_soal_sikk.pilihan_jawaban'
            )
            ->where('lembar_jawab_ikk.id', $id)
            ->first();

        if (!$lembarJawab) {
            return redirect()->route('ikk.lembar-jawab.index')
                ->with('error', 'Data tidak ditemukan');
        }

        return view('ikk.lembar-jawab.show', compact('lembarJawab'));
    }

    public function grafik(Request $request)
    {
        $tahun = $request->get('tahun', date('Y'));
        $opd = $request->get('opd');

        // Capaian per OPD
        $capaianQuery = DB::table('lembar_jawab_ikk')
            ->select('opd', DB::raw('AVG(capaian) as rata_rata'))
            ->where('tahun', $tahun)
            ->groupBy('opd');

        if ($opd) {
            $capaianQuery->where('opd', $opd);
        }

        $capaianData = $capaianQuery->get();

        // Trend capaian per tahun
        $trendQuery = DB::table('lembar_jawab_ikk')
            ->select('tahun', DB::raw('AVG(capaian) as rata_rata'))
            ->groupBy('tahun')
            ->orderBy('tahun', 'asc');

        if ($opd) {
            $trendQuery->where('opd', $opd);
        }

        $trendData = $trendQuery->get();

        // Status distribusi
        $statusQuery = DB::table('lembar_jawab_ikk')
            ->select('status', DB::raw('COUNT(*) as jumlah'))
            ->where('tahun', $tahun)
            ->groupBy('status');

        if ($opd) {
            $statusQuery->where('opd', $opd);
        }

        $statusData = $statusQuery->get();

        $chartData = [
            'capaianPerOPD' => [
                'labels' => $capaianData->pluck('opd')->toArray(),
                'data' => $capaianData->pluck('rata_rata')->toArray()
            ],
            'trendCapaian' => [
                'labels' => $trendData->pluck('tahun')->toArray(),
                'data' => $trendData->pluck('rata_rata')->toArray()
            ],
            'statusDistribusi' => [
                'labels' => $statusData->pluck('status')->toArray(),
                'data' => $statusData->pluck('jumlah')->toArray()
            ]
        ];

        $opdList = DB::table('lembar_jawab_ikk')
            ->select('opd')
            ->distinct()
            ->pluck('opd');

        $tahunList = DB::table('lembar_jawab_ikk')
            ->select('tahun')
            ->distinct()
            ->orderBy('tahun', 'desc')
            ->pluck('tahun');

        return view('ikk.lembar-jawab.grafik', compact('chartData', 'opdList', 'tahunList', 'tahun', 'opd'));
    }
}