<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\SubKriteria;
use App\Models\Kriteria;
use App\Models\Penilaian;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
use Carbon\Carbon;

class SubkriteriaController extends Controller
{
    public function index(Request $request, $kriteria = null)
    {
        if ($kriteria) {
        $kriteria = Kriteria::findOrFail($kriteria);
        $order = $kriteria->attribut == 'benefit' ? 'desc' : 'asc';
        $subkriterias = $kriteria->subkriteria()->orderBy('nilai', $order)->get();
    } else {
        // Gunakan chunk atau cursor jika data sangat besar
        $subkriterias = SubKriteria::with('kriteria')
            ->get()
            ->groupBy('kriteria_id')
            ->map(function ($items) {
                $order = $items->first()->kriteria->attribut == 'benefit' ? 'desc' : 'asc';
                return $order == 'desc' 
                    ? $items->sortByDesc('nilai') 
                    : $items->sortBy('nilai');
            })
            ->flatten();
    }

    return view('admin.subkriteria.index', compact('kriteria', 'subkriterias'));
}

    public function indexByKriteria(Kriteria $kriteria)
{
    $order = ($kriteria->attribut == 'benefit') ? 'desc' : 'asc';
    $subkriterias = $kriteria->subkriteria()
                        ->orderBy('nilai', $order)
                        ->get();

    return view('admin.subkriteria.index', [
        'kriteria' => $kriteria,
        'subkriterias' => $subkriterias
    ]);
}

    public function create(Request $request)
    {
        $kriteria = Kriteria::all();
        $selectedKriteria = $request->query('kriteria_id');
    
        // Validate if kriteria exists if provided
        if ($selectedKriteria && !Kriteria::find($selectedKriteria)) {
        abort(404, 'Kriteria tidak ditemukan');
        }
        
        return view('admin.subkriteria.create', [
            'kriterias' => $kriteria,
            'selectedKriteria' => $selectedKriteria
        ]);
    }

    public function store(Request $request)
    {
        try {
        $validated = $request->validate([
            'kriteria_id' => 'required|exists:kriteria,id',
            'nama_subkriteria' => [
                'required',
                'string',
                'max:255',
                Rule::unique('sub_kriterias')->where(function ($query) use ($request) {
                    return $query->where('kriteria_id', $request->kriteria_id);
                })
            ],
            'nilai' => 'required|integer|min:0|max:100'
        ]);

        $subkriteria = SubKriteria::create($validated);

        return redirect()->route('subkriteria.index', $subkriteria->kriteria)
            ->with('success', 'Sub kriteria berhasil ditambahkan');
    } catch (\Exception $e) {
        Log::error('Error creating subkriteria: ' . $e->getMessage());
        return redirect()->back()
            ->with('error', 'Gagal menambahkan sub kriteria: ' . $e->getMessage())
            ->withInput();
    }
}


    public function edit($id)
    {
        $subkriteria = SubKriteria::with('kriteria')->findOrFail($id);
        
        return view('admin.subkriteria.edit', [
            'subkriteria' => $subkriteria,
            'kriteria' => $subkriteria->kriteria
        ]);
    }

    public function update(Request $request, $id)
    {   
        try {
        $subkriteria = SubKriteria::findOrFail($id);
    
        $validated = $request->validate([
            'nama_subkriteria' => [
                'required',
                'string',
                'max:255',
                Rule::unique('sub_kriterias')
                    ->where('kriteria_id', $subkriteria->kriteria_id)
                    ->ignore($subkriteria->id)
            ],
            'nilai' => 'required|integer|min:0|max:100'
        ]);

        $subkriteria->update($validated);
    
        return redirect()->route('subkriteria.index', $subkriteria->kriteria_id)
            ->with('success', 'Sub kriteria berhasil diperbarui');
    } catch (\Exception $e) {
        Log::error('Error updating subkriteria: ' . $e->getMessage());
        return redirect()->back()
            ->with('error', 'Gagal memperbarui sub kriteria: ' . $e->getMessage())
            ->withInput();
    }
}

  public function destroy($id)
{
    try {
        $subkriteria = SubKriteria::findOrFail($id);
        $kriteriaId = $subkriteria->kriteria_id;
        $subkriteria->delete();

        return response()->json([
            'success' => true,
            'message' => 'Sub kriteria berhasil dihapus',
            'redirect' => route('subkriteria.index', ['kriteria' => $kriteriaId])
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Gagal menghapus sub kriteria: ' . $e->getMessage()
        ], 500);
    }
}

    public function downloadPDF($kriteria_id = null)
{
    $data = [];

    if ($kriteria_id) {
        $kriteria = Kriteria::findOrFail($kriteria_id);
        $subkriterias = $kriteria->subkriteria()
                           ->orderBy('nilai', $kriteria->attribut == 'benefit' ? 'desc' : 'asc')
                           ->get();

        $data['kriteria'] = $kriteria;
        $data['subkriterias'] = $subkriterias;
    } else {
        $allKriteria = Kriteria::with('subkriteria')->get();
        $grouped = [];

        foreach ($allKriteria as $krit) {
            $subs = $krit->subkriteria->sortBy(function ($sub) use ($krit) {
                return $krit->attribut == 'benefit' ? -$sub->nilai : $sub->nilai;
            })->values();

            $grouped[] = [
                'kriteria' => $krit,
                'subkriterias' => $subs
            ];
        }

        $data['kriteria'] = null;
        $data['grouped_subkriterias'] = $grouped;
    }

    $pdf = PDF::loadView('admin.subkriteria.subkriteria-pdf', $data);
    $filename = $kriteria_id 
        ? "Subkriteria-{$data['kriteria']->nama_kriteria}.pdf" 
        : "Semua-Subkriteria.pdf";

    return $pdf->stream($filename);
}}