<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Alternatif;
use App\Models\Penilaian;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Crips;
use Exception;

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

    public function index(){

        if(auth()->user()->role === 'admin') {
            $alternatifs = Alternatif::paginate(10); // Tambahkan pagination untuk efisiensi
        return view('admin.alternatif.index', compact('alternatifs'));
        } else {
           
            return view('user.alternatif.index',);
        }
 
    }

    public function store(Request $request){
        $validated = $request->validate([
            'nama_alternatif' => 'required|string|max:255',
            'usia' => 'required|numeric',
            'pendidikan' => 'required',
            'ipk' => 'required|numeric',
            'jurusan' => 'required',
            'lama_studi' => 'required|integer|min:0|max:10',
            'pengalaman' => 'required|integer|min:0|max:10',
            'serkom' => 'required',
            'cv' => 'required|file|mimes:pdf,doc,docx|max:2048',
            'dokumen_pendukung.*' => 'nullable|file|mimes:pdf,doc,docx,jpg,jpeg,png|max:2048',
        ]);

         // Upload CV
    if ($request->hasFile('cv')) {
        $validated['cv'] = $request->file('cv')->store('cv', 'public');
    }

    // Upload dokumen pendukung (opsional)
    $dokumenPendukungPaths = [];
    if ($request->hasFile('dokumen_pendukung')) {
        foreach ($request->file('dokumen_pendukung') as $file) {
            $dokumenPendukungPaths[] = $file->store('dokumen_pendukung', 'public');
        }
    }

    $validated['dokumen_pendukung'] = json_encode($dokumenPendukungPaths);
    
    $alternatif = Alternatif::create($validated);
    
    for ($kriteria_id = 1; $kriteria_id <= 7; $kriteria_id++) {
        $crips_id = $this->mapToCrips($alternatif, $kriteria_id);
        if ($crips_id) {
            Penilaian::create([
                'alternatif_id' => $alternatif->id,
                'kriteria_id' => $kriteria_id,
                'crips_id' => $crips_id,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }
        return redirect()->route('alternatif.index')->with('msg', 'Data pelamar berhasil ditambahkan!');

    }
    private function mapToCrips($alternatif, $kriteria_id)
    {
        $crips = Crips::where('kriteria_id', $kriteria_id)->get();
        $crips_id = null;

        switch ($kriteria_id) {
            case 1: // Usia
                $usia = $alternatif->usia;
                foreach ($crips as $crip) {
                    if ($crip->nama_crips == '23-24' && $usia >= 23 && $usia <= 24) $crips_id = $crip->id;
                    elseif ($crip->nama_crips == '25-26' && $usia >= 25 && $usia <= 26) $crips_id = $crip->id;
                    elseif ($crip->nama_crips == '27-28' && $usia >= 27 && $usia <= 28) $crips_id = $crip->id;
                    elseif ($crip->nama_crips == '29-30' && $usia >= 29 && $usia <= 30) $crips_id = $crip->id;
                    elseif ($crip->nama_crips == '> 30' && $usia > 30) $crips_id = $crip->id;
                }
                break;

            case 2: // Pendidikan
                $pendidikan = $alternatif->pendidikan;
                foreach ($crips as $crip) {
                    if ($crip->nama_crips == $pendidikan) $crips_id = $crip->id;
                }
                break;

            case 3: // IPK
                $ipk = $alternatif->ipk;
                foreach ($crips as $crip) {
                    if ($crip->nama_crips == '3.5-4.0' && $ipk >= 3.5 && $ipk <= 4.0) $crips_id = $crip->id;
                    elseif ($crip->nama_crips == '3.0-3.49' && $ipk >= 3.0 && $ipk < 3.5) $crips_id = $crip->id;
                    elseif ($crip->nama_crips == '2.75-2.99' && $ipk >= 2.75 && $ipk < 3.0) $crips_id= $crip->id;
                    elseif ($crip->nama_crips == '2.5-2.74' && $ipk >= 2.5 && $ipk < 2.75) $crips_id = $crip->id;
                }
                break;

            case 4: // Jurusan
                $jurusan = $alternatif->jurusan;
                foreach ($crips as $crip) {
                    if ($crip->nama_crips == $jurusan) $crips_id = $crip->id;
                }
                break;

            case 5: // Lama Studi
                $lama_studi = $alternatif->lama_studi;
                foreach ($crips as $crip) {
                    if ($crip->nama_crips == '<4 tahun' && $lama_studi < 4) $crips_id = $crip->id;
                    elseif ($crip->nama_crips == '4-5 tahun' && $lama_studi >= 4 && $lama_studi <= 5) $crips_id = $crip->id;
                    elseif ($crip->nama_crips == '>5 tahun' && $lama_studi > 5) $crips_id = $crip->id;
                }
                break;

            case 6: // Pengalaman
                $pengalaman = $alternatif->pengalaman;
                foreach ($crips as $crip) {
                    if ($crip->nama_crips == '>3 tahun' && $pengalaman > 3) $crips_id = $crip->id;
                    elseif ($crip->nama_crips == '1-3 tahun' && $pengalaman >= 1 && $pengalaman <= 3) $crips_id = $crip->id;
                
                }
                break;

            case 7: // Serkom
                $serkom = $alternatif->serkom;
                foreach ($crips as $crip) {
                    if ($crip->nama_crips == 'Punya' && $serkom == 1) $crips_id = $crip->id;
                    elseif ($crip->nama_crips == 'Tidak punya' && $serkom == 0) $crips_id = $crip->id;
                }
                break;
        }

        return $crips_id;
    }

    public function edit($id)
    {
        $data['alternatif'] = Alternatif::findOrFail($id);
        return view('admin.alternatif.edit', $data);
    }


    public function update(Request $request, $id)
{
    $validated = $request->validate([
        'nama_alternatif' => 'required|string|max:255',
        'usia' => 'required|integer|min:18',
        'pendidikan' => 'required|string',
        'ipk' => 'required|numeric|min:0|max:4',
        'jurusan' => 'required|string',
        'lama_studi' => 'required|integer   |min:0|max:10',
        'pengalaman' => 'required|integer|min:0|max:50',
        'serkom' => 'required|boolean',
    ]);

    try {
        $alternatif = Alternatif::findOrFail($id);
        $alternatif->update($validated);

        Penilaian::where('alternatif_id', $id)->delete();

        // Buat ulang penilaian berdasarkan data terbar
        return back()->with('msg','Berhasil Mengubah Data');
    } catch (Exception $e) {
        \Log::emergency("File:" . $e->getFile(). "Line:" . $e->getLine(). "Message:" . $e->getMessage());
        die("Gagal");
    }
}


    public function destroy($id){

        try {

            $alternatif = Alternatif::findOrFail($id);
            $alternatif->delete();
            Penilaian::where('alternatif_id', $id)->delete();

            return back()->with('msg', 'Data pelamar berhasil dihapus!');
        } 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');
        $alternatif = Alternatif::with('penilaian.crips')->get();

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