<?php

namespace App\Http\Controllers;

use App\Models\Job;
use App\Models\Skill;
use Illuminate\Http\Request;

class JobController extends Controller
{
    public function index()
    {
        // CompanyScope automatically filters by company_id
        $jobs = Job::with('creator')->latest()->paginate(10);
        return view('company.jobs.index', compact('jobs'));
    }

    public function create()
    {
        $skills = Skill::all();
        return view('company.jobs.create', compact('skills'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'budget_min' => 'nullable|numeric|min:0',
            'budget_max' => 'nullable|numeric|min:0|gte:budget_min',
            'job_type' => 'required|in:fixed,hourly',
            'deadline' => 'nullable|date|after:today',
            'skills' => 'nullable|array',
            'skills.*' => 'exists:skills,id',
        ]);

        $job = Job::create([
            'company_id' => auth()->user()->company_id,
            'created_by' => auth()->id(),
            'title' => $request->title,
            'description' => $request->description,
            'budget_min' => $request->budget_min,
            'budget_max' => $request->budget_max,
            'job_type' => $request->job_type,
            'deadline' => $request->deadline,
            'status' => 'open',
        ]);

        if ($request->has('skills')) {
            $job->skills()->sync($request->skills);
        }

        return redirect()->route('company.jobs.index')->with('success', 'Job posted successfully.');
    }

    public function edit(Job $job)
    {
        $skills = Skill::all();
        $jobSkills = $job->skills->pluck('id')->toArray();
        return view('company.jobs.edit', compact('job', 'skills', 'jobSkills'));
    }

    public function update(Request $request, Job $job)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'budget_min' => 'nullable|numeric|min:0',
            'budget_max' => 'nullable|numeric|min:0|gte:budget_min',
            'job_type' => 'required|in:fixed,hourly',
            'deadline' => 'nullable|date',
            'status' => 'required|in:open,closed',
            'skills' => 'nullable|array',
        ]);

        $job->update($request->except('skills'));

        if ($request->has('skills')) {
            $job->skills()->sync($request->skills);
        } else {
            $job->skills()->detach();
        }

        return redirect()->route('company.jobs.index')->with('success', 'Job updated successfully.');
    }

    public function destroy(Job $job)
    {
        $job->delete(); // Soft delete because of SoftDeletes trait
        return redirect()->route('company.jobs.index')->with('success', 'Job deleted successfully.');
    }
}
