<?php

namespace App\Http\Controllers;

use App\Models\JobListing;
use App\Models\Ad;
use App\Models\Application;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index(Request $request)
    {
        $query = JobListing::active()->latest();

        if ($request->filled('search')) {
            $search = str_replace(['%', '_'], ['\%', '\_'], $request->search);
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('company', 'like', "%{$search}%")
                  ->orWhere('location', 'like', "%{$search}%");
            });
        }

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

        $jobs = $query->paginate(12);
        $appliedJobIds = collect();

        if (session('applicant_id')) {
            $appliedJobIds = Application::where('applicant_id', session('applicant_id'))
                ->whereIn('job_listing_id', $jobs->pluck('id'))
                ->pluck('job_listing_id');
        }

        $bannerTop = Ad::getByPosition('banner_top');
        $bannerBottom = Ad::getByPosition('banner_bottom');
        $nativeAd = Ad::getByPosition('native');
        $mobileBanner = Ad::getByPosition('mobile_banner');

        return view('home', compact('jobs', 'appliedJobIds', 'bannerTop', 'bannerBottom', 'nativeAd', 'mobileBanner'));
    }

    public function show(JobListing $job)
    {
        if (!$job->is_active) abort(404);

        $job->load('stages');
        $bannerTop = Ad::getByPosition('banner_top');
        $nativeAd = Ad::getByPosition('native');
        $bannerBottom = Ad::getByPosition('banner_bottom');
        $sidebarAds = Ad::getAllByPosition('sidebar');
        $inArticleAd = Ad::getByPosition('in_article');
        $mobileBanner = Ad::getByPosition('mobile_banner');

        return view('job-detail', compact('job', 'bannerTop', 'nativeAd', 'bannerBottom', 'sidebarAds', 'inArticleAd', 'mobileBanner'));
    }
}
