<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use App\Http\Requests\add_job_request;
use App\Http\Requests\add_filter_request;
use App\Models\Job;
use App\Models\Apply;
use App\Models\User;
use App\Models\City;
use App\Models\Category;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class JobController extends Controller
{
    public function jobs(add_filter_request $request)
    {
        // Задаем переменные
        $all_jobs = Job::all();
        $filters = $request->all();
        // Извлекаем страницы пагинации из фильтров
        unset($filters['page']);
        $cities = City::all();
        $categories = Category::all();

        // Извлекаем минимальное и максимальное значение зарплаты из фильтра
        $minsalary = (int) Str::before($request->salary, '+');
        $maxsalary = (int) Str::after($request->salary, '-');

        // Удаляем фильтр зарплаты из массива фильтров
        unset($filters['salary']);

        $jobs = Job::where(function ($job) use ($filters) {
            foreach ($filters as $key => $value) {
                if ($value != null) {
                    if ($key == 'category_id') {
                        $job->whereIn($key, explode(',', $value));
                    } else {
                        $job->where($key, 'like', "%{$value}%");
                    }
                }
            }
        });

        if ($minsalary) {
            // Добавляем фильтр по зарплате
            $jobs = $jobs->whereBetween('salary', [$minsalary, $maxsalary]);
        }
        $req = $request;

        // Ищем имена отображаемых фильтров
        $cityreq = City::where('id', $req->city_id)->first();
        $categoryreq = Category::where('id', $req->category_id)->first();
        
        $jobs = $jobs->orderByDesc('created_at');
        // Preserve filters in the pagination links
        $jobs = $jobs->paginate(4)->appends($filters)->appends($request->except('page'));
        return view('jobs', ['jobs' => $jobs, 'all_jobs' => $all_jobs, 'minsalary' => $minsalary, 'maxsalary' => $maxsalary, 'cities' => $cities, 'categories' => $categories, 'req' => $req, 'cityreq' => $cityreq, 'categoryreq' => $categoryreq]);
    }

    public function index(add_filter_request $request)
    {
        $jobs = Job::all();
        $users = User::where('role', 'user')->get();
        $pcategories = Category::withCount('job')->get()->sortByDesc('job_count');
        return view('index', ['jobs' => $jobs, 'users' => $users, 'pcategories' => $pcategories]);
    }

    public function jobs_details($job)
    {
        $job = Job::with('user')->find($job);

        $apply = Apply::where('job_id', $job)->get();
        
        return view('jobs_details', ['job' => $job, 'apply' => $apply]);
    }

    public function addjob(add_job_request $request)
    {
        $job = new Job();
        $job->user_id = Auth::id();
        $job->name = $request->name;
        $job->category_id = $request->category;
        $job->city_id = $request->city;
        $job->job_count = $request->job_count;
        $job->salary = $request->salary;
        $job->jobnature = $request->jobnature;
        $job->description = $request->description;
        $job->icon = Storage::disk('public')->put('icons', $request->file('icon'));
        $job->save();

        return redirect()->route('index');
    }
    
    public function add_job()
    {
        $cities = City::all();
        $categories = Category::all();
        return view('add_job', ['cities' => $cities, 'categories' => $categories]);
    }

    public function edit_job($job)
    {
        $job = Job::where('id', $job)->first();
        $cities = City::all();
        $categories = Category::all();
        return view('edit_job', ['cities' => $cities, 'categories' => $categories, 'job' => $job]);
    }

    public function editjob(Request $request, Job $job){
        $job->name = $request->name;
        $job->job_count = $request->job_count;
        $job->salary = $request->salary;
        $job->jobnature = $request->jobnature;
        $job->description = $request->description;
        if($request->icon){
            $job->icon = Storage::disk('public')->put('icons', $request->file('icon'));
        }
        $job->save();
        return redirect()->route('jobs_details', $job->id);
    }

    public function deletejob(Job $job){
        $job->delete();
        return redirect()->route('jobs');
    }
}
