<?php

namespace App\Http\Controllers\Site;

use App\Http\Controllers\Controller;
use App\Models\JobApplication;
use App\Models\JobListing;
use App\Models\Media;
use App\Models\Page;
use App\Support\AdminNotifier;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class CareersController extends Controller
{
    public function index(): View
    {
        $page = Page::query()
            ->published()
            ->where('route_path', '/careers')
            ->with('sections')
            ->first();

        $jobs = JobListing::query()->openPublic()->latest()->get();

        return view('site.careers.index', compact('page', 'jobs'));
    }

    public function show(JobListing $job): View
    {
        abort_unless($job->is_published && $job->status === 'open', 404);
        if ($job->closing_date && $job->closing_date->isPast()) {
            abort(404);
        }

        return view('site.careers.show', [
            'job' => $job,
        ]);
    }

    public function apply(Request $request, JobListing $job): RedirectResponse
    {
        abort_unless($job->is_published && $job->status === 'open', 404);
        if ($job->closing_date && $job->closing_date->isPast()) {
            abort(404);
        }

        $validated = $request->validate([
            'full_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'cover_note' => ['nullable', 'string', 'max:5000'],
            'cv' => ['required', 'file', 'mimes:pdf,doc,docx', 'max:5120'],
        ]);

        $path = $validated['cv']->store('uploads/cvs', 'public');
        $media = Media::query()->create([
            'disk' => 'public',
            'path' => $path,
            'filename' => $validated['cv']->getClientOriginalName(),
            'mime_type' => $validated['cv']->getClientMimeType(),
            'size_bytes' => $validated['cv']->getSize(),
        ]);

        $application = JobApplication::query()->create([
            'job_listing_id' => $job->id,
            'full_name' => $validated['full_name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'] ?? null,
            'cover_note' => $validated['cover_note'] ?? null,
            'cv_media_id' => $media->id,
        ]);

        AdminNotifier::trySend('New job application: '.$job->title, [
            'Role: '.$job->title,
            'Applicant: '.$application->full_name,
            'Email: '.$application->email,
            'Phone: '.($application->phone ?? '—'),
            'CV: '.$media->filename,
        ]);

        return redirect()
            ->route('careers.show', $job)
            ->with('status', 'Thank you. Your application has been received.');
    }
}
