<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Job;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class jobsController extends Controller
{
    public function all_jobs(){
        $jobs = Job::all();
        return response()->json([
            'message' => 'Jobs list get successfully!',
            'data' => $jobs
        ], 200);
    }
    public function add_job(Request $request){
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'location' => 'required|string|max:255',
            'salary' => 'required|integer|min:0', // Ensure salary is a positive integer
            'type' => 'required|in:full-time,part-time,temporary', // Ensure valid enum value
        ]);

        // Insert the new job into the jobs table
        $job = DB::table('jobs')->insert([
            'title' => $request->title,
            'description' => $request->description,
            'location' => $request->location,
            'salary' => $request->salary,
            'type' => $request->type,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Return a success response
        return response()->json([
            'message' => 'Job added successfully!',
            'data' => $job
        ], 200);
    }
    public function filter_jobs(Request $request){
        // return $request;
        $request->validate([
            'locations' => 'array|nullable',
            'locations.*' => 'string|distinct',
            'types' => 'array|nullable',
            'types.*' => 'in:full-time,part-time,temporary',
            'salary_ranges' => 'array|nullable',
            'salary_ranges.*' => 'regex:/^\d{1,5}-\d{1,5}$/', // Ensure salary ranges are in "min-max" format
        ]);

        // Start building the query
        $query = DB::table('jobs');

        // Filter by locations if provided
        if ($request->has('locations') && count($request->locations) > 0) {
            $query->orWhereIn('location', $request->locations);
        }

        // Filter by types if provided
        if ($request->has('types') && count($request->types) > 0) {
            $query->orWhereIn('type', $request->types);
        }

        // Filter by salary ranges if provided
        if ($request->has('salary_ranges') && count($request->salary_ranges) > 0) {
            foreach ($request->salary_ranges as $range) {
                list($minSalary, $maxSalary) = explode('-', $range);

                $query->whereBetween('salary', [(int) $minSalary, (int) $maxSalary]);
            }
        }

        // Get the filtered jobs
        $jobs = $query->get();

        // Return the results
        return response()->json([
            'message' => 'Jobs fetched successfully!',
            'data' => $jobs,
        ]);
    }
}
