<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Jobs\ScanCvWithVirusTotal;
use App\Models\JobApplication;
use App\Models\JobPosting;
use App\Models\SiteSetting;
use App\Services\ApplicationExcelMergeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\ApplicationsExport;

class ApplicationController extends Controller
{
    public function index(Request $request)
    {
        $query = JobApplication::with('jobPosting')->whereNull('purged_at');

        if ($request->filled('job_posting_id')) {
            $query->where('job_posting_id', $request->job_posting_id);
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('department')) {
            $query->whereHas('jobPosting', fn($q) => $q->where('department', $request->department));
        }
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('full_name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        // Varsayılan olarak geçmiş (reddedildi/işe_alındı) başvuruları gizle
        if (!$request->filled('status')) {
            $query->whereNotIn('status', ['reddedildi', 'işe_alındı']);
        }

        $applications = $query->latest()->paginate(25);
        $jobPostings = JobPosting::orderBy('title')->get();
        $departments = JobPosting::distinct()->pluck('department')->sort()->values();

        // İstatistik kartları için durum bazlı sayımlar (purge edilmemiş başvurular)
        $stats = [
            'total'              => JobApplication::whereNull('purged_at')->count(),
            'yeni'               => JobApplication::whereNull('purged_at')->where('status', 'yeni')->count(),
            'incelendi'          => JobApplication::whereNull('purged_at')->where('status', 'incelendi')->count(),
            'gorusmeye_cagirildi'=> JobApplication::whereNull('purged_at')->where('status', 'görüşmeye_çağrıldı')->count(),
            'reddedildi'         => JobApplication::whereNull('purged_at')->where('status', 'reddedildi')->count(),
            'ise_alindi'         => JobApplication::whereNull('purged_at')->where('status', 'işe_alındı')->count(),
        ];

        return view('admin.basvurular.index', compact('applications', 'jobPostings', 'departments', 'stats'));
    }

    /**
     * KVKK: Manuel purge — sadece super-admin
     */
    public function kvkkPurge(Request $request)
    {
        // Yetki kontrolü: sadece super-admin
        if (!auth()->user()->hasRole('super-admin')) {
            abort(403, 'Bu işlem için yetkiniz yok.');
        }

        $retentionDays = (int) SiteSetting::get('kvkk_retention_days', 90);
        $cutoff = now()->subDays($retentionDays);

        $applications = JobApplication::where('created_at', '<', $cutoff)
            ->whereNull('purged_at')
            ->get();

        $count = $applications->count();

        if ($count === 0) {
            return back()->with('success', 'Silinecek eski başvuru bulunamadı.');
        }

        foreach ($applications as $application) {
            // CV dosyasını sil
            if ($application->cv_path && Storage::disk('local')->exists($application->cv_path)) {
                Storage::disk('local')->delete($application->cv_path);
            }

            // Kişisel verileri anonimleştir
            $application->update([
                'full_name'        => 'Silindi',
                'email'            => 'silindi_' . $application->id . '@kvkk.local',
                'phone'            => null,
                'cover_letter'     => null,
                'cv_path'          => null,
                'cv_original_name' => null,
                'linkedin_url'     => null,
                'internal_notes'   => null,
                'kvkk_consent_ip'  => null,
                'purged_at'        => now(),
            ]);
        }

        \Illuminate\Support\Facades\Log::info('KVKK Manuel Purge', [
            'by_user'   => auth()->id(),
            'count'     => $count,
            'cutoff'    => $cutoff->toDateTimeString(),
        ]);

        return back()->with('success', "{$count} başvurunun kişisel verileri KVKK gereği temizlendi.");
    }

    public function gecmis(Request $request)
    {
        $query = JobApplication::with('jobPosting')
            ->whereNull('purged_at')
            ->whereIn('status', ['reddedildi', 'işe_alındı']);

        if ($request->filled('job_posting_id')) {
            $query->where('job_posting_id', $request->job_posting_id);
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('full_name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $applications = $query->latest()->paginate(25);
        $jobPostings = JobPosting::orderBy('title')->get();

        return view('admin.basvurular.gecmis', compact('applications', 'jobPostings'));
    }

    public function show(JobApplication $application)
    {
        $application->load('jobPosting', 'reviewer');

        $activities = \Spatie\Activitylog\Models\Activity::with('causer')
            ->where('subject_type', JobApplication::class)
            ->where('subject_id', $application->id)
            ->latest()
            ->get();

        return view('admin.basvurular.show', compact('application', 'activities'));
    }

    public function updateStatus(Request $request, JobApplication $application)
    {
        $request->validate([
            'status' => 'required|in:yeni,incelendi,görüşmeye_çağrıldı,reddedildi,işe_alındı',
        ]);

        $application->update([
            'status'      => $request->status,
            'reviewed_by' => auth()->id(),
        ]);

        return back()->with('success', 'Başvuru durumu güncellendi.');
    }

    public function updateNotes(Request $request, JobApplication $application)
    {
        $request->validate([
            'internal_notes' => 'nullable|string|max:5000',
        ]);

        $application->update(['internal_notes' => $request->internal_notes]);

        return back()->with('success', 'Not kaydedildi.');
    }

    public function downloadCv(JobApplication $application)
    {
        if (!$application->cv_path || !Storage::disk('local')->exists($application->cv_path)) {
            abort(404, 'CV dosyası bulunamadı.');
        }

        return Storage::disk('local')->download(
            $application->cv_path,
            $application->cv_original_name
        );
    }

    public function viewCv(JobApplication $application)
    {
        if (!$application->cv_path || !Storage::disk('local')->exists($application->cv_path)) {
            abort(404, 'CV dosyası bulunamadı.');
        }

        $path = Storage::disk('local')->path($application->cv_path);
        $mimeType = Storage::disk('local')->mimeType($application->cv_path) ?: 'application/octet-stream';

        // Sadece PDF ve resim dosyaları inline gösterilir
        $inlineMimes = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif', 'image/webp'];

        if (!in_array($mimeType, $inlineMimes)) {
            // Desteklenmeyen format → indirme olarak sun
            return Storage::disk('local')->download(
                $application->cv_path,
                $application->cv_original_name
            );
        }

        // Dosya adını sanitize et — header injection'a karşı
        $safeFilename = preg_replace('/[^\w\-.]/', '_', basename($application->cv_original_name));

        return response()->file($path, [
            'Content-Type'        => $mimeType,
            'Content-Disposition' => 'inline; filename="' . $safeFilename . '"',
        ]);
    }

    public function bulkStatus(Request $request)
    {
        $request->validate([
            'ids'    => 'required|array',
            'ids.*'  => 'integer|exists:job_applications,id',
            'status' => 'required|in:yeni,incelendi,görüşmeye_çağrıldı,reddedildi,işe_alındı',
        ]);

        JobApplication::whereIn('id', $request->ids)->update([
            'status'      => $request->status,
            'reviewed_by' => auth()->id(),
        ]);

        return back()->with('success', count($request->ids) . ' başvurunun durumu güncellendi.');
    }

    public function export(Request $request, JobPosting $jobPosting)
    {
        $format = $request->get('format', 'xlsx');
        $filename = 'basvurular-' . $jobPosting->slug . '-' . now()->format('Y-m-d');

        if ($format === 'csv') {
            return Excel::download(new ApplicationsExport($jobPosting->id), $filename . '.csv', \Maatwebsite\Excel\Excel::CSV);
        }

        return Excel::download(new ApplicationsExport($jobPosting->id), $filename . '.xlsx');
    }

    public function mergeExcel(Request $request, JobPosting $jobPosting, ApplicationExcelMergeService $mergeService)
    {
        $request->validate([
            'excel_file' => 'required|file|mimes:xlsx,xls,csv|max:10240',
        ]);

        $uploadedFile = $request->file('excel_file');
        $result = $mergeService->merge($uploadedFile, $jobPosting->id);

        return response()->download($result['path'], $result['filename'])->deleteFileAfterSend(true);
    }

    /**
     * CV tarama durumunu JSON olarak döndür (polling için)
     */
    public function cvScanStatus(JobApplication $application)
    {
        $application->refresh();

        return response()->json([
            'status'       => $application->cv_scan_status,
            'status_label' => $application->cv_scan_status_label,
            'status_color' => $application->cv_scan_status_color,
            'scanned_at'   => $application->cv_scanned_at?->format('d.m.Y H:i'),
            'is_final'     => !in_array($application->cv_scan_status, ['pending']),
        ]);
    }

    /**
     * CV'yi tekrar tara (manuel tetikleme)
     */
    public function rescan(JobApplication $application)
    {
        if (!$application->cv_path || !Storage::disk('local')->exists($application->cv_path)) {
            return back()->with('error', 'CV dosyası bulunamadı, tekrar tarama yapılamaz.');
        }

        $application->update([
            'cv_scan_status' => 'pending',
            'cv_scan_result' => null,
            'cv_scanned_at'  => null,
        ]);

        ScanCvWithVirusTotal::dispatch($application);

        return back()->with('success', 'CV taraması kuyruğa alındı. Sonuç birkaç dakika içinde güncellenecek.');
    }

}
