<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\JobPosting;
use Illuminate\Http\Request;

class OpenRolesController extends Controller
{
    public function index(Request $request)
    {
        $search = trim((string) $request->get('search', ''));
        $departmentId = $request->integer('department_id') ?: null;
        $employmentType = trim((string) $request->get('employment_type', ''));

        $baseQuery = JobPosting::query()->where('status', 'active');

        $stats = [
            'roles' => (clone $baseQuery)->count(),
            'openings' => (int) (clone $baseQuery)->sum('openings'),
            'departments' => (int) (clone $baseQuery)->whereNotNull('department_id')->distinct()->count('department_id'),
            'locations' => (int) (clone $baseQuery)->whereNotNull('location')->where('location', '!=', '')->distinct()->count('location'),
        ];

        $jobPostings = JobPosting::query()
            ->with('department')
            ->where('status', 'active')
            ->when($search !== '', function ($query) use ($search) {
                $query->where(function ($inner) use ($search) {
                    $inner->where('title', 'like', '%'.$search.'%')
                        ->orWhere('location', 'like', '%'.$search.'%')
                        ->orWhere('description', 'like', '%'.$search.'%');
                });
            })
            ->when($departmentId, fn ($query) => $query->where('department_id', $departmentId))
            ->when($employmentType !== '', fn ($query) => $query->where('employment_type', $employmentType))
            ->orderByDesc('posted_at')
            ->orderByDesc('created_at')
            ->paginate(12)
            ->withQueryString();

        $departments = JobPosting::query()
            ->where('status', 'active')
            ->whereNotNull('department_id')
            ->with('department')
            ->get()
            ->pluck('department')
            ->filter()
            ->unique('id')
            ->sortBy('name')
            ->values();

        $employmentTypes = JobPosting::query()
            ->where('status', 'active')
            ->whereNotNull('employment_type')
            ->where('employment_type', '!=', '')
            ->distinct()
            ->orderBy('employment_type')
            ->pluck('employment_type');

        return view('recruitment.open-roles', compact(
            'jobPostings',
            'stats',
            'search',
            'departmentId',
            'employmentType',
            'departments',
            'employmentTypes'
        ));
    }
}
