WorkerController.php 13.1 KB
<?php

namespace App\Http\Controllers;

use App\Classes\RusDate;
use App\Models\Ad_employer;
use App\Models\Category;
use App\Models\Employer;
use App\Models\Job_title;
use App\Models\Message;
use App\Models\reclame;
use App\Models\Static_worker;
use App\Models\User;
use App\Models\User as User_Model;
use App\Models\Worker;
use Carbon\Carbon;
use Illuminate\Auth\Events\Registered;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class WorkerController extends Controller
{
    public $status_work = array(0 => 'Ищу работу', 1 => 'Не указано', 2 => 'Не ищу работу');

    //профиль
    public function profile(Worker $worker)
    {
        $get_date = date('Y.m');

        $c = Static_worker::query()->where('year_month', '=', $get_date)
            ->where('user_id', '=', $worker->users->id)
            ->get();

        if ($c->count() > 0) {
            $upd = Static_worker::find($c[0]->id);
            $upd->lookin = $upd->lookin + 1;
            $upd->save();
        } else {
            $crt = new Static_worker();
            $crt->lookin = 1;
            $crt->year_month = $get_date;
            $crt->user_id = $worker->user_id;
            $crt->save();
        }

        $stat = Static_worker::query()->where('year_month', '=', $get_date)
            ->where('user_id', '=', $worker->users->id)
            ->get();

        return view('public.workers.profile', compact('worker', 'stat'));
    }

    // лист база резюме
    public function bd_resume()
    {
        $status_work = $this->status_work;
        $resumes = Worker::query()->with('users')->with('job_titles');

        $res_count = $resumes->count();
        $resumes = $resumes->paginate(5);

        return view('resume', compact('resumes', 'status_work', 'res_count'));
    }

    // анкета соискателя
    public function resume_profile(Worker $worker)
    {
        $status_work = $this->status_work;
        $Query = Worker::query()->with('users')->with('job_titles')
            ->with('place_worker')->with('sertificate')->with('prev_company')
            ->with('infobloks');
        $Query = $Query->where('id', '=', $worker->id);
        $Query = $Query->get();
        return view('worker', compact('Query', 'status_work'));
    }

    // скачать анкету соискателя
    public function resume_download(Worker $worker)
    {
        print_r('Резюме для скачивания');
    }

    // Кабинет работника
    public function cabinet()
    {
        $id = Auth()->user()->id;
        $Worker = Worker::query()->with('sertificate')->
        with('infobloks')->with('place_worker')->
        WhereHas('users',
            function (Builder $query) use ($id) {$query->Where('id', $id);
            })->get();
        dd($Worker);
        return view('workers.cabinet', compact('Worker'));
    }

    // Сохранение данных
    public function cabinet_save(Worker $worker, Request $request)
    {

    }

    // Сообщения данные
    public function messages($type_message)
    {
        $user_id = Auth()->user()->id;

        $messages_input = Message::query()->with('vacancies')->with('user_from')->
        Where('to_user_id', $user_id)->OrderByDesc('created_at');

        $messages_output = Message::query()->with('vacancies')->
        with('user_to')->where('user_id', $user_id)->
        OrderByDesc('created_at');


        $count_input = $messages_input->count();
        $count_output = $messages_output->count();

        if ($type_message == 'input') {
            $messages = $messages_input->paginate(15);
        }

        if ($type_message == 'output') {
            $messages = $messages_output->paginate(15);
        }
        // Вернуть все 100%
        return view('workers.messages', compact('messages', 'count_input', 'count_output', 'type_message', 'user_id'));
    }

    // Избранный
    public function favorite()
    {
        dd('dgfghfghfgh');
        return view('workers.favorite');
    }


    // Сменить пароль
    public function new_password()
    {
        $email = Auth()->user()->email;
        return view('workers.new_password', compact('email'));
    }

    // Обновление пароля
    public function save_new_password(Request $request) {
        $use = Auth()->user();
        $request->validate([
            'password' => 'required|string',
            'new_password' => 'required|string',
            'new_password2' => 'required|string'
        ]);

        if ($request->get('new_password') == $request->get('new_password2'))
            if ($request->get('password') !== $request->get('new_password')) {
                $credentials = $request->only('email', 'password');
                if (Auth::attempt($credentials)) {

                    if (!is_null($use->email_verified_at)){

                        $user_data = User_Model::find($use->id);
                        $user_data->update([
                            'password' => Hash::make($request->get('new_password')),
                            'pubpassword' => base64_encode($request->get('new_password')),
                        ]);
                        return redirect()
                            ->route('worker.new_password')
                            ->with('success', 'Поздравляю! Вы обновили свой пароль!');
                    }

                    return redirect()
                        ->route('worker.new_password')
                        ->withError('Данная учетная запись не было верифицированна!');
                }
            }

        return redirect()
            ->route('worker.new_password')
            ->withErrors('Не совпадение данных, обновите пароли!');
    }

    // Удаление профиля форма
    public function delete_profile()
    {
        $login = Auth()->user()->email;
        return view('workers.delete_profile', compact('login'));
    }

    // Удаление профиля код
    public function delete_profile_result(Request $request) {
        $Answer = $request->all();
        $user_id = Auth()->user()->id;
        $request->validate([
            'password' => 'required|string',
        ]);

        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {
            Auth::logout();
            $it = User_Model::find($user_id);
            //$it->delete();
            return redirect()->route('index')->with('success', 'Вы успешно удалили свой аккаунт');
        } else {
            return redirect()->route('worker.delete_profile')
                ->withErrors( 'Неверный пароль! Нужен корректный пароль');
        }
    }

    // Регистрация соискателя
    public function register_worker(Request $request)
    {
        $params = $request->all();

        $rules = [
            'surname' => ['required', 'string', 'max:255'],
            'name_man' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8'],
        ];

        $messages = [
            'required' => 'Укажите обязательное поле',
            'min' => [
                'string' => 'Поле «:attribute» должно быть не меньше :min символов',
                'integer' => 'Поле «:attribute» должно быть :min или больше',
                'file' => 'Файл «:attribute» должен быть не меньше :min Кбайт'
            ],
            'max' => [
                'string' => 'Поле «:attribute» должно быть не больше :max символов',
                'integer' => 'Поле «:attribute» должно быть :max или меньше',
                'file' => 'Файл «:attribute» должен быть не больше :max Кбайт'
            ]
        ];




        if ($request->get('password') !== $request->get('confirmed')){
            return json_encode(Array("ERROR" => "Error: Не совпадают пароль и подтверждение пароля"));
        }

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            return json_encode(Array("ERROR" => "Error1: Регистрация оборвалась ошибкой! Не все обязательные поля заполнены. Либо вы уже были зарегистрированы в системе."));
        } else {
            $user = $this->create($params);
            event(new Registered($user));

            Auth::guard()->login($user);
        }
        if ($user) {
            return json_encode(Array("REDIRECT" => redirect()->route('worker.cabinet')->getTargetUrl()));;
        } else {
            return json_encode(Array("ERROR" => "Error2: Данные были утеряны!"));
        }
    }

    // Создание пользователя
    protected function create(array $data)
    {
        $Use = new User();
        $Code_user = $Use->create([
                            'name' => $data['surname']." ".$data['name_man'],
                            'name_man' => $data['name_man'],
                            'surname' => $data['surname'],
                            'surname2' => $data['surname2'],
                            'subscribe_email' => $data['email'],
                            'email' => $data['email'],
                            'telephone' => $data['telephone'],
                            'password' => Hash::make($data['password']),
                            'pubpassword' => base64_encode($data['password']),
                            'email_verified_at' => Carbon::now()
                        ]);
        if ($Code_user->id > 0) {
            $Worker = new Worker();
            $Worker->user_id = $Code_user->id;
            $Worker->position_work = $data['job_titles'];
            $Worker->email = $data['email'];
            $Worker->telephone = $data['telephone'];
            $Worker->save();

            return $Code_user;
        }
    }

    // Борьба против колорадских жуков, хотя жуков победил все таки 45.
    public function colorado(Request $request) {
        if (isset($_COOKIE['favorite_vac'])) {
            $items = RusDate::count_vacancy_fav();
            $it = $_COOKIE['favorite_vac'];
            $it = str_replace('"', "", $it);
            $it = str_replace('[', "", $it);
            $it = str_replace(']', "", $it);
            $Arr = explode(",", $it);
        } else {
            $Arr = Array();
        }

        $Query = Ad_employer::Query();
        if (count($Arr) > 0) {
            $Query = $Query->whereIn('id', $Arr);
        }
        $Query = $Query->with('jobs')->
        with('cat')->
        with('employer')->
        whereHas('jobs_code', function ($query) use ($request) {
            if ($request->ajax()) {
                if (null !== ($request->get('job'))) {
                    $query->where('job_title_id', $request->get('job'));
                }
            }
        })->select('ad_employers.*');

        $Job_title = Job_title::query()->OrderBy('name')->get();

        $Query_count = $Query->count();

        $Query = $Query->OrderBy('updated_at')->paginate(3);

        return view('workers.favorite', compact('Query',
                                                    'Query_count',
                                                                'Job_title'));

    }

    //Переписка пись-пись-пись
    public function dialog(User_Model $user1, User_Model $user2) {
        if (isset($user2->id)) {
            $companion = User_Model::query()->with('workers')->
            with('employers')->
            where('id', $user2->id)->first();
        }

        $Messages = Message::query()->with('response')->where(function($query) use ($user1, $user2) {
            $query->where('user_id', $user1->id)->where('to_user_id', $user2->id);
        })->orWhere(function($query) use ($user1, $user2) {
            $query->where('user_id', $user2->id)->where('to_user_id', $user1->id);
        })->OrderBy('created_at')->get();

        $id_vac = null;
        foreach ($Messages as $it) {
            if (isset($it->response)) {
                foreach ($it->response as $r) {
                    if (isset($r->ad_employer_id)) {
                        $id_vac = $r->ad_employer_id;
                        break;
                    }
                }
            }
            if (!is_null($id_vac)) break;
        }

        $ad_employer = null;
        if (!is_null($id_vac)) $ad_employer = Ad_employer::query()->where('id', $id_vac)->first();
        $sender = $user1;

        return view('workers.dialog', compact('companion', 'sender', 'Messages', 'ad_employer'));
    }
}