<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Penilaian;
use App\Models\Alternatif;
use App\Models\Kriteria;
use App\Models\Crips;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;
use PDF;



class PenilaianController extends Controller
{
    public function index(){
        $alternatif = Alternatif::with('penilaian.crips')->get();
        $kriteria = Kriteria::with('crips')->orderBy('id','ASC')->get();
        //return response()->json($alternatif);
            return view('admin.penilaian.index', compact('alternatif', 'kriteria'));
        

    }
 
    public function store(Request $request)
    {
        try {
            DB::table('penilaian')->truncate(); // lebih aman
    
            $kriteria = Kriteria::orderBy('id', 'ASC')->get(); // urutan penting
    
            foreach ($request->crips_id as $alternatif_id => $crips_list) {
                foreach ($crips_list as $index => $crips_id) {
                    Penilaian::create([
                        'alternatif_id' => $alternatif_id,
                        'kriteria_id'   => $kriteria[$index]->id, // ambil kriteria berdasarkan urutan
                        'crips_id'      => $crips_id
                    ]);
                }
            }
    
            return back()->with('msg', 'Berhasil Disimpan!');
        } catch (Exception $e) {
            Log::emergency("File:" . $e->getFile(). "Line:" . $e->getLine(). "Message:" . $e->getMessage());
            die("Gagal");
        }
    }
    

    public function downloadPDF() {
        setlocale(LC_ALL, 'IND');
        $tanggal = Carbon::now()->formatLocalized('%A, %d %B %Y');
        // $penilaian = Kriteria::get();
        // $alternatif = Alternatif::with('penilaian.crips')->get();
        // $kriteria = Kriteria::with('crips')->get();
        $alternatifs = Alternatif::with('penilaian.crips')->get();
        $kriteria = Kriteria::with('crips')->orderBy('nama_kriteria','ASC')->get();
        $penilaian = Penilaian::with('crips','alternatif')->get();

        $pdf = PDF::loadView('admin.penilaian.penilaian-pdf',compact('kriteria','tanggal','alternatif','penilaian'));
        $pdf->setPaper('A3', 'potrait');
        return $pdf->stream('penilaian.pdf');
    }
}
