<?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\LamaranUser;
use App\Models\Crips;
use Illuminate\Support\Facades\Storage;
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 terimaLamaran($id)
    {
        $lamaran = LamaranUser::findOrFail($id);

      $alternatif = Alternatif::create([
            'nama_alternatif' => $lamaran->name,
            'usia' => $lamaran->usia,
            'pendidikan' => $lamaran->pendidikan,
            'ipk' => $lamaran->ipk,
            'jurusan' => $lamaran->jurusan,
            'lama_studi' => $lamaran->lama_studi,
            'pengalaman' => $lamaran->pengalaman,
            'serkom' => $lamaran->serkom,
            'cv' => $lamaran->cv,
            'dokumen_pendukung' => $lamaran->dokumen_pendukung,
        ]);

        // Hapus dari tabel lamaran_users
        $kriteria = \App\Models\Kriteria::all(); // pastikan sudah ada model Kriteria

        foreach ($kriteria as $k) {
            $crips_id = $this->mapToCrips($alternatif, $k->id);
            if ($crips_id) {
                Penilaian::create([
                    'alternatif_id' => $alternatif->id,
                    'kriteria_id' => $k->id,
                    'crips_id' => $crips_id
                ]);
                }   
             }
        
            $lamaran->delete();

    return redirect()->back()->with('msg', 'Lamaran berhasil diterima dan dipindahkan ke data pelamar.');
            }
       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;
                    elseif ($crip->nama_crips == '2.0-2.49' && $ipk >= 2.0 && $ipk < 2.49) $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)
{
    \DB::beginTransaction();
    try {
        $alternatif = Alternatif::findOrFail($id);

        // Hapus file CV
        if ($alternatif->cv) {
            \Storage::disk('public')->delete($alternatif->cv);
        }

        // Hapus dokumen pendukung
        if ($alternatif->dokumen_pendukung) {
            $docs = json_decode($alternatif->dokumen_pendukung, true);
            foreach ($docs as $doc) {
                \Storage::disk('public')->delete($doc);
            }
        }

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

        \DB::commit();
        return response()->json(['message' => 'Data pelamar berhasil dihapus!'], 200);
    } catch (\Exception $e) {
        \DB::rollBack();
        \Log::emergency("File:" . $e->getFile() . " Line:" . $e->getLine() . " Message:" . $e->getMessage());
        return response()->json(['error' => 'Gagal menghapus data'], 500);
    }
}

    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');
    }
    public function tolakLamaran($id)
    {
        $lamaran = LamaranUser::findOrFail($id);

        // Hapus file yang diupload
        if (Storage::disk('public')->exists($lamaran->cv)) {
            Storage::disk('public')->delete($lamaran->cv);
        }

        if ($lamaran->dokumen_pendukung) {
            foreach (json_decode($lamaran->dokumen_pendukung, true) as $file) {
                if (Storage::disk('public')->exists($file)) {
                    Storage::disk('public')->delete($file);
                }
            }
        }

        $lamaran->delete();

        return redirect()->back()->with('msg', 'Lamaran ditolak dan data telah dihapus.');
    }
}
