<?php

namespace App\Http\Controllers;

use App\Models\JobPosting;
use Illuminate\Http\Request;

class JobController extends Controller
{
    // For Workers: Search jobs
    public function index(Request $request)
    {
        $query = JobPosting::query()->with('client.clientProfile');

        $query->where('status', 'open');

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

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

        // Simple date filter
        if ($request->filled('date')) {
            $query->whereDate('start_time', $request->date);
        }

        return $query->latest()->paginate(10);
    }

    // For Clients: Store a new job
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string',
            'role_type' => 'required|string',
            'description' => 'nullable|string',
            'location' => 'required|string',
            'postcode' => 'required|string',
            'start_time' => 'required|date',
            'end_time' => 'required|date|after:start_time',
            'rate_per_hour' => 'required|numeric|min:0',
            'requirements' => 'nullable|array',
        ]);

        $job = JobPosting::create([
            'client_id' => $request->user()->id,
            'title' => $request->title,
            'role_type' => $request->role_type,
            'description' => $request->description,
            'location' => $request->location,
            'postcode' => $request->postcode,
            'start_time' => $request->start_time,
            'end_time' => $request->end_time,
            'rate_per_hour' => $request->rate_per_hour,
            'status' => 'open', // defaulted to open for MVP
            'requirements' => $request->requirements,
        ]);

        return response()->json($job, 201);
    }

    // For Clients: List their own jobs
    public function myJobs(Request $request)
    {
        return $request->user()->clientProfile->jobPostings()->latest()->get();
    }
}
