<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreApplicationRequest;
use App\Jobs\ScanCvWithVirusTotal;
use App\Models\JobApplication;
use App\Models\JobPosting;
use App\Models\SiteSetting;
use App\Notifications\ApplicationReceivedNotification;
use App\Notifications\NewApplicationAdminNotification;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Models\User;

class JobController extends Controller
{
    public function show(string $slug)
    {
        $job = JobPosting::where('slug', $slug)
            ->where('status', '!=', 'draft')
            ->firstOrFail();

        $similarJobs = collect();

        if (!$job->isOpen()) {
            $similarJobs = JobPosting::published()
                ->where('id', '!=', $job->id)
                ->where('department', $job->department)
                ->limit(3)
                ->get();
        }

        return view('public.job-detail', compact('job', 'similarJobs'));
    }

    public function apply(StoreApplicationRequest $request, string $slug)
    {
        $job = JobPosting::where('slug', $slug)
            ->where('status', 'published')
            ->firstOrFail();

        if (!$job->isOpen()) {
            return back()->with('error', 'Bu pozisyon için başvurular kapanmıştır.');
        }

        // Honeypot kontrolü
        if ($request->filled('website')) {
            return redirect()->route('job.show', $slug)->with('success', 'Başvurunuz alındı.');
        }

        // CV dosyasını güvenli şekilde kaydet
        $file = $request->file('cv');
        $originalName = $file->getClientOriginalName();
        $extension = $file->guessExtension() ?? $file->getClientOriginalExtension();

        // MIME type sunucu tarafında kontrol
        $allowedMimes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
        if (!in_array($file->getMimeType(), $allowedMimes)) {
            return back()->withErrors(['cv' => 'Geçersiz dosya türü. Yalnızca PDF, DOC veya DOCX kabul edilmektedir.'])->withInput();
        }

        // UUID ile yeniden adlandır
        $newFileName = Str::uuid() . '.' . $extension;
        $cvPath = $file->storeAs('cvs/' . $job->id, $newFileName, 'local');

        // Başvuruyu kaydet
        $application = JobApplication::create([
            'job_posting_id'  => $job->id,
            'department_id'   => $job->department_id,
            'full_name'       => $request->full_name,
            'email'           => $request->email,
            'phone'           => $request->phone,
            'cover_letter'    => $request->cover_letter,
            'cv_path'         => $cvPath,
            'cv_original_name' => $originalName,
            'linkedin_url'    => $request->linkedin_url,
            'source'          => $request->source,
            'kvkk_consent'    => true,
            'kvkk_consent_at' => now(),
            'kvkk_consent_ip' => $request->ip(),
            'status'          => 'yeni',
        ]);

        // E-posta bildirimleri (queue ile)
        try {
            $application->notify(new ApplicationReceivedNotification($job));

            $admins = User::role(['super-admin', 'hr-manager'])->get();
            Notification::send($admins, new NewApplicationAdminNotification($application, $job));
        } catch (\Exception $e) {
            // Mail hatası başvuruyu engellemez
            \Illuminate\Support\Facades\Log::error('Başvuru bildirimi gönderilemedi: ' . $e->getMessage());
        }

        // VirusTotal CV tarama — sadece otomatik modda kuyruğa at
        $cvScanMode = SiteSetting::get('cv_scan_mode', 'otomatik');
        if ($cvScanMode === 'otomatik') {
            try {
                ScanCvWithVirusTotal::dispatch($application);
            } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('CV scan dispatch hatası: ' . $e->getMessage());
            }
        } else {
            // Manuel mod: taranmadı olarak işaretle, admin istediğinde tetikler
            $application->update(['cv_scan_status' => 'skipped']);
        }

        return redirect()->route('job.show', $slug)
            ->with('success', 'Başvurunuz başarıyla alındı! En kısa sürede sizinle iletişime geçeceğiz.');
    }
}