<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\LamaranUser;
use App\Notifications\PelamarBaruNotification;
use Illuminate\Support\Facades\Notification;
use App\Models\User;
class LamaranUserController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'usia' => 'required|integer|min:17|max:60',
            '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',
            'cv' => 'required|file|mimes:pdf,doc,docx|max:2048',
            'dokumen_pendukung.*' => 'nullable|file|mimes:pdf,doc,docx,jpg,png|max:2048',
        ]);

        // Upload CV
        $cvPath = $request->file('cv')->store('dokumen/cv', 'public');

        // Upload dokumen pendukung (bisa lebih dari satu file)
        $dokumenPaths = [];
        if ($request->hasFile('dokumen_pendukung')) {
            foreach ($request->file('dokumen_pendukung') as $file) {
                $dokumenPaths[] = $file->store('dokumen/pendukung', 'public');
            }
        }

      $lamaran =  LamaranUser::create([
            'name' => $request->name,
            'usia' => $request->usia,
            'pendidikan' => $request->pendidikan,
            'ipk' => $request->ipk,
            'jurusan' => $request->jurusan,
            'lama_studi' => $request->lama_studi,
            'pengalaman' => $request->pengalaman,
            'serkom' => $request->serkom,
            'cv' => $cvPath,
            'dokumen_pendukung' => json_encode($dokumenPaths),
        ]);
        $adminUsers = User::where('role', 'admin')->get(); // Pastikan 'role' sesuai
        Notification::send($adminUsers, new PelamarBaruNotification([
            'message' => "Pelamar baru: {$lamaran->name}"
        ]));
        return redirect()->back()->with('msg', 'Lamaran Anda berhasil diajukan. Silakan tunggu konfirmasi dari admin.');
    }
}
