<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\LamaranUser;
use App\Models\Alternatif;
use Illuminate\Support\Facades\Storage;

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

    // Tampilkan daftar lamaran yang belum dikonfirmasi
    public function daftarLamaran()
    {
        $lamarans = LamaranUser::latest()->get();
        return view('admin.home.blade', compact('lamarans'));
    }

    // Admin menerima lamaran dan memindahkan ke tabel alternatif
    public function terimaLamaran($id)
    {
        $lamaran = LamaranUser::findOrFail($id);

        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
        $lamaran->delete();

        return redirect()->back()->with('msg', 'Lamaran berhasil diterima dan dipindahkan ke data pelamar.');
    }

    // ✅ Admin menolak lamaran dan menghapus datanya
    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.');
    }
}
