<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\Department;
use App\Models\JobPosting;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index(Request $request)
    {
        $query = JobPosting::published();

        // Arama (başlık üzerinden)
        if ($request->filled('search')) {
            $query->where('title', 'like', '%' . trim($request->search) . '%');
        }

        if ($request->filled('department')) {
            $query->where('department', $request->department);
        }

        if ($request->filled('location')) {
            $query->where('location', $request->location);
        }

        if ($request->filled('employment_type')) {
            $query->where('employment_type', $request->employment_type);
        }

        // Öne çıkan ilanlar önce, sonra yayın tarihine göre
        $jobs = $query->orderByDesc('is_featured')->latest('published_at')->get();

        // Filtre seçenekleri
        $departments     = JobPosting::published()->distinct()->pluck('department')->sort()->values();
        $locations       = JobPosting::published()->distinct()->pluck('location')->sort()->values();
        $employmentTypes = JobPosting::published()->distinct()->pluck('employment_type')->sort()->values();

        // Aktif departmanlar (admin panelinden yönetilir) + her birinin açık ilan sayısı
        $activeDepartments = Department::active()->orderBy('sort_order')->get();

        // Her departman için yayındaki ilan sayısını hesapla
        $jobCountByDept = JobPosting::published()
            ->selectRaw('department, count(*) as cnt')
            ->groupBy('department')
            ->pluck('cnt', 'department');

        // Genel başvuru kabul eden departmanlar
        $openDepartments = Department::acceptsApplications()->orderBy('sort_order')->get();

        return view('public.home', compact(
            'jobs',
            'departments',
            'locations',
            'employmentTypes',
            'activeDepartments',
            'openDepartments',
            'jobCountByDept'
        ));
    }
}