<?php

namespace App\Http\Controllers\Admin;

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

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

    public function index()
    {
        $opds = OPD::withCount('responses')->orderBy('name')->get();
        return view('admin.opds.index', compact('opds'));
    }

    public function create()
    {
        return view('admin.opds.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:opds,code',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        OPD::create([
            'name' => $request->name,
            'code' => strtoupper($request->code),
            'description' => $request->description,
            'is_active' => $request->has('is_active'),
        ]);

        return redirect()->route('admin.opds.index')
            ->with('success', 'OPD berhasil ditambahkan.');
    }

    public function show($id)
    {
        $opd = OPD::withCount('responses')->findOrFail($id);
        return view('admin.opds.show', compact('opd'));
    }

    public function edit($id)
    {
        $opd = OPD::findOrFail($id);
        return view('admin.opds.edit', compact('opd'));
    }

    public function update(Request $request, $id)
    {
        $opd = OPD::findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:opds,code,' . $id,
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $opd->update([
            'name' => $request->name,
            'code' => strtoupper($request->code),
            'description' => $request->description,
            'is_active' => $request->has('is_active'),
        ]);

        return redirect()->route('admin.opds.index')
            ->with('success', 'OPD berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $opd = OPD::findOrFail($id);
        
        // Check if OPD is being used
        if ($opd->responses()->count() > 0) {
            return redirect()->route('admin.opds.index')
                ->with('error', 'OPD tidak dapat dihapus karena sedang digunakan dalam response.');
        }

        $opd->delete();

        return redirect()->route('admin.opds.index')
            ->with('success', 'OPD berhasil dihapus.');
    }

    public function results($id, Request $request)
    {
        $opd = OPD::findOrFail($id);
        $tahun = $request->get('tahun', date('Y'));

        // Get available years for this OPD
        $tahunList = DB::table('lembar_jawab_ikk')
            ->where('opd', $opd->name)
            ->select('tahun')
            ->distinct()
            ->orderBy('tahun', 'desc')
            ->pluck('tahun');

        // Get IKK results for this OPD and year
        $hasilIkk = DB::table('lembar_jawab_ikk')
            ->join('bank_soal_sikk', 'lembar_jawab_ikk.bank_soal_id', '=', 'bank_soal_sikk.id')
            ->where('lembar_jawab_ikk.opd', $opd->name)
            ->where('lembar_jawab_ikk.tahun', $tahun)
            ->select(
                'lembar_jawab_ikk.*',
                'bank_soal_sikk.kode_ikk',
                'bank_soal_sikk.ikk_output',
                'bank_soal_sikk.satuan',
                'bank_soal_sikk.urusan',
                'bank_soal_sikk.bidang'
            )
            ->orderBy('bank_soal_sikk.kode_ikk', 'asc')
            ->get();

        // Calculate statistics
        $totalIkk = $hasilIkk->count();
        $diverifikasi = $hasilIkk->where('status', 'DIVERIFIKASI')->count();
        $diajukan = $hasilIkk->where('status', 'DIAJUKAN')->count();
        $perluPerbaikan = $hasilIkk->where('status', 'PERLU PERBAIKAN')->count();
        $draft = $hasilIkk->where('status', 'DRAFT')->count();

        // Calculate average capaian (only for verified)
        $rataCapaian = $hasilIkk->where('status', 'DIVERIFIKASI')->avg('capaian');

        return view('admin.opds.results', compact('opd', 'tahun', 'tahunList', 'hasilIkk',
            'totalIkk', 'diverifikasi', 'diajukan', 'perluPerbaikan', 'draft', 'rataCapaian'));
    }
}



