<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PengajuanUkt;
use App\Models\Kriteria;
use App\Models\Form;
use App\Services\SawCalculationService;
use Exception;

class PenilaianController extends Controller
{
    protected $sawService;

    public function __construct(SawCalculationService $sawService)
    {
        $this->sawService = $sawService;
    }

   public function index(Request $request)
{
    $query = PengajuanUkt::with(['mahasiswa.user', 'hasilPenilaian'])
        ->where('status_validasi', 'valid');

    if ($request->has('status_form_id') && $request->status_form_id != '') {
        $query->where('status_form_id', $request->status_form_id);
    }

    $validPengajuans = $query->orderByDesc('created_at')
        ->paginate(10)
        ->appends($request->query());

    $forms = Form::orderBy('nama_form')->get();

    return view('admin.penilaian.index', compact('validPengajuans', 'forms'));
}

    public function calculateAll()
    {
        $validIds = PengajuanUkt::where('status_validasi', 'valid')
            ->pluck('id')
            ->toArray();

        // Proses langsung tanpa queue untuk local
        $result = $this->sawService->processBatch($validIds);

        return redirect()->route('admin.ranking.index')
            ->with('success', 'Berhasil memproses '.$result['success_count'].' dari '.count($validIds).' pengajuan');
    }

    public function calculate($id)
    {
        $pengajuan = PengajuanUkt::with('details')->findOrFail($id);

        $hasil = $this->sawService->calculate($pengajuan);

        $kriterias = Kriteria::whereIn('id', array_keys($hasil['decision_matrix']))
            ->get()
            ->keyBy('id');

        return view('admin.penilaian.result', compact('pengajuan', 'hasil', 'kriterias'));
    }

    public function processBatch(Request $request)
{
    $request->validate([
        'limit' => 'required|integer|min:1|max:100'
    ]);

    try {
        $pengajuanIds = PengajuanUkt::where('status_validasi', 'valid')
            ->whereDoesntHave('hasilPenilaian')
            ->limit($request->limit)
            ->pluck('id')
            ->toArray();

        if (empty($pengajuanIds)) {
            return redirect()->back()
                ->with('info', 'Semua pengajuan valid sudah diproses');
        }

        $result = $this->sawService->processBatch($pengajuanIds);

        return redirect()->route('admin.penilaian.index')
            ->with('success', 'Berhasil memproses '.$result['success_count'].' data pengajuan!');

    } catch (Exception $e) {
        return redirect()->back()
            ->with('error', 'Gagal memproses: '.$e->getMessage());
    }
}

    public function result($id)
{
    $pengajuan = PengajuanUkt::with(['mahasiswa.user', 'details.subKriteria', 'hasilPenilaian'])
        ->findOrFail($id);
    
    if (!$pengajuan->hasilPenilaian) {
        return redirect()->route('admin.penilaian.index')
            ->with('error', 'Data ini belum diproses');
    }

    try {
        // Get full calculation details from service
        $hasil = $this->sawService->getCalculationDetails($pengajuan->id);
        
        // Get all kriterias with their subkriteria
        $kriterias = Kriteria::with('subKriteria')->get()->keyBy('id');
        
        return view('admin.penilaian.result', [
            'pengajuan' => $pengajuan,
            'hasil' => $hasil,
            'kriterias' => $kriterias
        ]);

    } catch (Exception $e) {
        return redirect()->back()
            ->with('error', 'Gagal menampilkan hasil: '.$e->getMessage());
    }
}}