<?php

namespace App\Http\Controllers;

use App\Models\JobApplication;
use App\Models\JobPosting;
use Illuminate\Http\Request;

class PublicCareerController extends Controller
{
    public function index()
    {
        return view('careers.index', [
            'jobs' => JobPosting::with('department')->where('status', 'open')->latest()->paginate(10),
        ]);
    }

    public function show(JobPosting $job)
    {
        abort_if($job->status !== 'open', 404);
        return view('careers.show', ['job' => $job->load('department')]);
    }

    public function apply(Request $request, JobPosting $job)
    {
        abort_if($job->status !== 'open', 404);
        $data = $request->validate([
            'full_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'cv' => ['nullable', 'file', 'max:5120'],
            'cover_letter' => ['nullable', 'string'],
        ]);
        if ($request->hasFile('cv')) {
            $data['cv_path'] = $request->file('cv')->store('candidate-cvs', 'public');
        }
        unset($data['cv']);
        $data['job_posting_id'] = $job->id;
        $data['status'] = 'new';
        JobApplication::create($data);

        return redirect()->route('careers.show', $job)->with('success', 'Application submitted successfully.');
    }
}
