<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Department;
use App\Models\JobPosting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class JobPostingController extends Controller
{
    public function index()
    {
        $jobPostings = JobPosting::with('department')
            ->withCount('applicants')
            ->latest()
            ->paginate(12);
        $activeCount = JobPosting::where('status', 'active')->count();

        return view('recruitment.job-postings.index', compact('jobPostings', 'activeCount'));
    }

    public function create()
    {
        $departments = Department::orderBy('name')->get();
        return view('recruitment.job-postings.create', compact('departments'));
    }

    public function store(Request $request)
    {
        $companyId = Auth::user()?->company_id;
        $validated = $request->validate([
            'title' => ['required', 'string', 'max:191'],
            'department_id' => ['nullable', 'exists:departments,id'],
            'location' => ['nullable', 'string', 'max:191'],
            'employment_type' => ['required', 'string', 'max:50'],
            'openings' => ['required', 'integer', 'min:1'],
            'status' => ['required', Rule::in(['active', 'closed'])],
            'posted_at' => ['nullable', 'date'],
            'description' => ['nullable', 'string'],
        ]);

        JobPosting::create(array_merge($validated, [
            'company_id' => $companyId,
        ]));

        return redirect()->route('job-postings.index')->with('success', 'Job posting created successfully.');
    }

    public function edit(JobPosting $jobPosting)
    {
        $departments = Department::orderBy('name')->get();
        return view('recruitment.job-postings.edit', compact('jobPosting', 'departments'));
    }

    public function update(Request $request, JobPosting $jobPosting)
    {
        $validated = $request->validate([
            'title' => ['required', 'string', 'max:191'],
            'department_id' => ['nullable', 'exists:departments,id'],
            'location' => ['nullable', 'string', 'max:191'],
            'employment_type' => ['required', 'string', 'max:50'],
            'openings' => ['required', 'integer', 'min:1'],
            'status' => ['required', Rule::in(['active', 'closed'])],
            'posted_at' => ['nullable', 'date'],
            'description' => ['nullable', 'string'],
        ]);

        $jobPosting->update($validated);

        return redirect()->route('job-postings.index')->with('success', 'Job posting updated successfully.');
    }

    public function destroy(JobPosting $jobPosting)
    {
        $jobPosting->delete();

        return redirect()->route('job-postings.index')->with('success', 'Job posting deleted successfully.');
    }
}
