EmployerController.php 33.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
<?php

namespace App\Http\Controllers;

use App\Classes\RusDate;
use App\Classes\Tools;
use App\Http\Requests\BaseUser_min_Request;
use App\Http\Requests\FlotRequest;
use App\Http\Requests\MessagesRequiest;
use App\Http\Requests\VacancyRequestEdit;
use App\Mail\MailCreateEmployer;
use App\Mail\MailSotrudnichestvo;
use App\Mail\MassSendingMessages;
use App\Mail\SendAllMessages;
use App\Models\Ad_employer;
use App\Models\ad_response;
use App\Models\Category;
use App\Models\Chat;
use App\Models\Employer;
use App\Models\EmployerAutoliftOption;
use App\Models\Flot;
use App\Models\Job_title;
use App\Models\Like_worker;
use App\Models\Message;
use App\Models\Worker;
use App\Models\MessagesRequests;
use Carbon\Carbon;
use Illuminate\Auth\Events\Registered;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use App\Models\User as User_Model;
use Illuminate\Support\Facades\Validator;
use App\Enums\DbExportColumns;
use Illuminate\View\View;
use JsonException;
use Throwable;

class EmployerController extends Controller
{
    public function vacancie($vacancy, Request $request) {
        $title = 'Заголовок вакансии';
        $Query = Ad_employer::with('jobs')->
                              with('cat')->
                              with('employer')->
                              with('jobs_code')->
                              select('ad_employers.*')->
                              where('id', '=', $vacancy)->get();

        if ($Query[0]->active_is===0 || $Query[0]->is_remove!=0){

          abort(404);

        }

        if (isset(Auth()->user()->id))
            $uid = Auth()->user()->id;
        else
            $uid = 0;
        $title = $Query[0]->name;
        if ($request->ajax()) {
            return view('ajax.vacance-item', compact('Query','uid'));
        } else {
            return view('vacance-item', compact('title', 'Query', 'uid'));
        }
    }

    public function logout() {
        Auth::logout();
        return redirect()->route('index')
            ->with('success', 'Вы вышли из личного кабинета');
    }

    public function employer_info() {
        // код юзера
        $user_info = Auth()->user();
        // вьюшка для вывода данных
        return view('employers.info', compact('user_info'));
    }

    public function employer_info_save(User_Model $user, BaseUser_min_Request $request) {
        // Все данные через реквест
        $all = $request->all();
        unset($all['_token']);
        // обновление
        $user->update($all);
        return redirect()->route('employer.employer_info');
    }

    public function cabinet() {
        $id = Auth()->user()->id;
        $Employer = Employer::query()->with('users')->with('ads')->with('flots')->
                                        WhereHas('users',
                                            function (Builder $query) use ($id) {$query->Where('id', $id);
                                        })->get();
        return view('employers.cabinet45', compact('Employer'));
    }

    public function slider_flot() {
        $id = Auth()->user()->id;
        $Employer = Employer::query()->with('users')->with('ads')->with('flots')->
        WhereHas('users',
            function (Builder $query) use ($id) {$query->Where('id', $id);
            })->get();
        return view('employers.fly-flot', compact('Employer'));
    }

    public function cabinet_save(Employer $Employer, Request $request) {
        $params = $request->all();
        $params['user_id'] = Auth()->user()->id;
        $id = $Employer->id;

        if ($request->has('logo')) {
            if (!empty($Employer->logo)) {
                Storage::delete($Employer->logo);
            }
            $params['logo'] = $request->file('logo')->store("employer/$id", 'public');
        }

        $Employer->update($params);

        return redirect()->route('employer.cabinet')->with('success', 'Данные были успешно сохранены');
    }

    public function save_add_flot(FlotRequest $request) {
        // отмена
        $params = $request->all();

        if ($request->has('image')) {
            $params['image'] = $request->file('image')->store("flot", 'public');
        }
        Flot::create($params);
        $data_flots = Flot::query()->where('employer_id', $request->get('employer_if'))->get();
        return redirect()->route('employer.slider_flot')->with('success', 'Новый корабль был добавлен');
    }

    public function edit_flot(Flot $Flot, Employer $Employer) {
        return view('employers.edit-flot', compact('Flot', 'Employer'));
    }

    public function update_flot(FlotRequest $request, Flot $Flot) {
        $params = $request->all();

        if ($request->has('image')) {
            if (!empty($flot->image)) {
                Storage::delete($flot->image);
            }
            $params['image'] = $request->file('image')->store("flot", 'public');
        } else {
            if (!empty($flot->image)) $params['image'] = $flot->image;
        }

        $Flot->update($params);
        return redirect()->route('employer.slider_flot')->with('success', 'Новый корабль был добавлен');
    }

    public function delete_flot(Flot $Flot) {
        $data_flots = Flot::query()->where('employer_id', $Flot->employer_id)->get();

        if (isset($Flot->id)) $Flot->delete();
        return redirect()->route('employer.slider_flot')->with('success', 'Корабль был удален');
    }

    // Форма добавления вакансий
    public function cabinet_vacancie() {
        /** @var User_Model $user */
        $user = Auth()->user();

        if ($user->is_public) {
            $categories = Category::query()->active()->get();

            $jobs = Job_title::query()
                ->orderByDesc('sort')
                ->OrderBy('name')
                ->where('is_remove', '=', '0')
                ->where('is_bd', '=', '0')
                ->get();

            $Employer = Employer::query()
                ->with(['users', 'ads', 'flots'])
                ->whereHas('users', fn (Builder $query) => $query->where('id', $user->id))
                ->get();

            return view('employers.add_vacancy', compact('Employer', 'jobs', 'categories'));
        }

        return redirect()->route('employer.cabinet_vacancie_danger');
    }

    // Форма предупреждения об оплате
    public function cabinet_vacancie_danger() {
        return view('employers.add_vacancy_danger');
    }

    // Сохранение вакансии
    public function cabinet_vacancy_save1(VacancyRequestEdit $request) {
        $params_emp = $request->all();

        $params_job["job_title_id"] = $params_emp['job_title_id'];

        $ad_jobs = Ad_employer::create($params_emp);
        $ad_jobs->jobs()->sync($request->get('job_title_id'));

        return redirect()->route('employer.vacancy_list')->with('success', 'Вакансия успешно опубликована');
    }

    // Список вакансий
    public function vacancy_list(Request $request) {
        $id = Auth()->user()->id;

        $Employer = Employer::query()->where('user_id', $id)->first();
        $vacancy_list = Ad_employer::query()
            ->with('jobs')
            ->with('jobs_code')
            ->where('employer_id', $Employer->id)
            ->where('is_remove', 0)
            ->orderbyDesc('updated_at')
        ;

        if (($request->has('search')) && (!empty($request->get('search')))) {
            $search = $request->get('search');
            $vacancy_list = $vacancy_list->where('name', 'LIKE', "%$search%");
        }

        if ($request->get('sort')) {
            $sort = $request->get('sort');
            switch ($sort) {
                case 'nopublic': $vacancy_list->orderByDesc('updated_at')
                    ->where('active_is', 0);
                    break;
                case 'public': $vacancy_list->orderByDesc('updated_at')
                    ->where('active_is',1);
                    break;
                default: $vacancy_list->orderByDesc('updated_at');
                    break;
            }
        } else {
            $vacancy_list = $vacancy_list->orderByDesc('updated_at')->orderBy('id');
        }

        $vacancy_list = $vacancy_list->paginate(10);

        if ($request->ajax()) {
            return view('employers.ajax.list_vacancy', compact('vacancy_list', 'Employer'));
        } else {
            return view('employers.list_vacancy', compact('vacancy_list', 'Employer'));
        }
    }

    // Карточка вакансии
    public function vacancy_edit(Ad_employer $ad_employer) {
        $id = Auth()->user()->id;
        $Positions = Category::query()->where('is_remove', '=', '0')->get();

        $jobs = Job_title::query()->orderByDesc('sort')->OrderBy('name')->
            where('is_remove', '=', '0')->
            where('is_bd', '=', '0')->get();

        $Employer = Employer::query()->with('users')->with('ads')->
                                       with('flots')->where('user_id', $id)->first();

        return view('employers.edit_vacancy', compact('ad_employer', 'Positions','Employer', 'jobs'));
    }

    // Сохранение-редактирование записи
    public function vacancy_save_me(VacancyRequestEdit $request, Ad_employer $ad_employer) {
        $params = $request->all();

        $ad_employer->update($params);
        $ad_employer->active_is = 1;
        $ad_employer->save();
        $ad_employer->jobs()->sync($request->get('job_title_id'));

        $id = Auth()->user()->id;
        $Positions = Category::query()->where('is_remove', '=', '0')->get();
        $jobs = Job_title::query()->orderByDesc('sort')->OrderBy('name')
            ->where('is_remove', '=', '0')
            ->where('is_bd', '=', '0')
            ->get();

        $Employer = Employer::query()
            ->with('users')->with('ads')->with('flots')->where('user_id', $id)->first();

        return redirect()->route('employer.vacancy_list')->with('success', 'Вакансия успешно отредактирована');
    }

    // Сохранение карточки вакансии
    public function vacancy_save(Request $request, Ad_employer $ad_employer) {
        $all = $request->all();
        $ad_employer->update($all);
        return redirect()->route('employer.cabinet_vacancie');
    }

    // Удаление карточки вакансии
    public function vacancy_delete(Ad_employer $ad_employer) {
        $ad_employer->delete();

        return redirect()->route('employer.vacancy_list')
            ->with('success', 'Вакансия удалена');
    }

    // Обновление даты
    public function vacancy_up(Ad_employer $ad_employer) {
        $up = date('m/d/Y h:i:s', time());
        $ad_employer->updated_at = $up;
        $ad_employer->save();

        return redirect()->route('employer.vacancy_list')
            ->with('success', 'Вакансия поднята');
    }

    //Видимость вакансии
    public function vacancy_eye(Ad_employer $ad_employer, $status) {
        $statusMessages = [
            'Вакансия скрыта',
            'Вакансия видна работникам'
        ];

        $vac_emp = Ad_employer::findOrFail($ad_employer->id);
        $vac_emp->active_is = $status;
        $vac_emp->save();

        return redirect()->route('employer.vacancy_list')
            ->with('success', $statusMessages[$status]);
    }

    //Вакансия редактирования (шаблон)
    public function vacancy_update(Ad_employer $id) {

    }

    //Отклики на вакансию - лист
    public function answers(Employer $employer, Request $request) {
        $user_id = Auth()->user()->id;
        $answer = Ad_employer::query()->where('employer_id', $employer->id);
        if ($request->has('search')) {
            $search = trim($request->get('search'));
            if (!empty($search)) $answer = $answer->where('name', 'LIKE', "%$search%");
        }

        $answer = $answer->with('response')->OrderByDESC('id')->get();

        return view('employers.list_answer', compact('answer', 'user_id', 'employer'));
    }

    //Обновление статуса
    public function supple_status(employer $employer, ad_response $ad_response,  $flag) {
        $ad_response->update(Array('flag' => $flag));
        return redirect()->route('employer.answers', ['employer' => $employer->id]);
    }

    //Страницы сообщений список
    public function messages($type_message) {
        $user_id = Auth()->user()->id;
        $superAdmin =User_Model::superAdmin();
        $chats = Chat::get_user_chats($user_id);
        $admin_chat = Chat::get_user_admin_chat($user_id);
        $user_type = 'employer';

        return view('employers.messages', compact('chats', 'admin_chat', 'user_id', 'user_type','superAdmin'));
    }

    // Диалог между пользователями
    public function dialog(Chat $chat, Request $request) {
        // Получение параметров.
        if ($request->has('ad_employer')){
            $ad_employer = $request->get('ad_employer');
        } else {
            $ad_employer = 0;
        }
        $superAdmin =User_Model::superAdmin();

        $sender = User_Model::query()->with('workers')->with('employers')->where('id', $chat->user_id)->first();
        $companion = User_Model::query()->with('workers')->with('employers')->where('id', $chat->to_user_id)->first();

        $Messages = Chat::get_chat_messages($chat);

        Message::where('user_id', '=', $chat->to_user_id)->where('to_user_id', '=', $chat->user_id)->update(['flag_new' => 0]);

        return view('employers.dialog', compact('companion', 'sender', 'ad_employer', 'Messages','chat','superAdmin'));
    }

    public function pin_chat(Request $request){
        $chat_id = $request->get('id');
        $is_fixed = $request->get('is_fixed');

        $new_state = Chat::pin_chat($chat_id, $is_fixed);

        if ($new_state !== null) {
            $message = $new_state ? 'Сообщение закреплено' : 'Сообщение откреплено';
            return redirect()->back()->with('success', $message);
        }

        return redirect()->back()->withErrors(['message' => 'Ошибка: сообщение не удалось обновить.']);
    }

    public function remove_chat(Request $request){
        $chat_id = $request->get('id');
        Chat::remove_chat($chat_id);
    }

    // Регистрация работодателя
    public function register_employer(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'],
            'name_company' => ['required', 'string', 'max:255'],
            'password' => ['required', 'string', 'min:6'],
        ];

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

        $email =  $request->get('email');
        if (!preg_match("/^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/", $email)) {
            return json_encode(Array("ERROR" => "Error: Отсутствует емайл или некорректный емайл"));
        }

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

        if (strlen($request->get('password')) < 6) {
            return json_encode(Array("ERROR" => "Error: Недостаточная длина пароля! Увеличьте себе длину пароля!"));
        }

        if (empty($request->get('surname'))) {
            $params['surname'] = 'Неизвестно';
        }
        if (empty($request->get('name_man'))) {
            $params['name_man'] = 'Неизвестно';
        }
        $validator = Validator::make($params, $rules, $messages);

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

            try {
                Mail::to(env('EMAIL_ADMIN'))->send(new MailCreateEmployer($params));
            } catch (Throwable $e) {
                Log::error($e);
            }

            Auth::guard()->login($user);
        }

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

    // Создание пользователя
    protected function create(array $data)
    {
        $Use = new User_Model();
        $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'],
            'is_worker' => 0,
            'password' => Hash::make($data['password']),
            'pubpassword' => base64_encode($data['password']),
            'email_verified_at' => Carbon::now()
        ]);

        if ($Code_user->id > 0) {
            $Employer = new Employer();
            $Employer->user_id = $Code_user->id;
            $Employer->name_company = $data['name_company'];
            $Employer->email = $data['email'];
            $Employer->telephone = $data['telephone'];
            $Employer->code = Tools::generator_id(10);
            $Employer->save();

            return $Code_user;
        }
    }

    // Отправка сообщения от работодателя
    public function send_message(MessagesRequiest $request) {
        $params = $request->all();

        $user1 = $params['user_id'];
        $user2 = $params['to_user_id'];

        if ($request->has('file')) {
            $params['file'] = $request->file('file')->store("messages", 'public');
        }
        Message::create($params);
        return redirect()->route('employer.dialog', ['user1' => $user1, 'user2' => $user2]);
    }

    public function test123(Request $request) {
        $params = $request->all();
        $user1 = $params['user_id'];
        $user2 = $params['to_user_id'];

        $rules = [
            'text' => 'nullable|required_without:file|min:1|max:150000',
            'file' => 'nullable|file|mimes:doc,docx,xlsx,csv,txt,xlx,xls,pdf|max:150000'
        ];
        $messages = [
            'required_without' => 'Поле «:attribute» обязательно, если файл не прикреплен',
            'min' => [
                'string' => 'Поле «:attribute» должно быть не меньше :min символов',
                'integer' => 'Поле «:attribute» должно быть :min или больше',
                'file' => 'Файл «:attribute» должен быть не меньше :min Кбайт'
            ],
            'max' => [
                'string' => 'Поле «:attribute» должно быть не больше :max символов',
                'integer' => 'Поле «:attribute» должно быть :max или меньше',
                'file' => 'Файл «:attribute» должен быть не больше :max Кбайт'
            ]
        ];

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

        if ($validator->fails()) {
            return redirect()->route('cabinet.messages', ['type_message' => 'input'])->withErrors($validator);
        }

        $new_message = Message::add_message($request, $user1, $user2, $request->all(), file_store_path: 'messages');
        return redirect()->route('employer.dialog', ['chat' => $new_message->chat_id_from]);

    }

    //Избранные люди
    public function favorites(Request $request)
    {
        $likedWorkersIds = Like_worker::query()
            ->where('user_id', Auth::user()->id)
            ->get()
            ->pluck('code_record')
            ->toArray();

        $workerBuilder = Worker::query()
            ->whereIn('id', $likedWorkersIds);

        if (($request->has('search')) && (!empty($request->get('search')))) {
            $search = $request->get('search');

            $workerBuilder->whereHas('users', function (Builder $query) use ($search) {
                $query->where('surname', 'LIKE', "%$search%")
                    ->orWhere('name_man', 'LIKE', "%$search%")
                    ->orWhere('surname2', 'LIKE', "%$search%");
            });
        }

        $Workers = $workerBuilder->get();

        return view('employers.favorite', compact('Workers'));
    }

    // База данных
    public function bd(Request $request) {
        if (!Auth::user()->show_database) {
            return redirect()->route('employer.employer_info');
        }

        $users = User_Model::query()->with('workers')->with('jobtitles');

        if ($request->has('search')) {
            $find_key = $request->get('search');
            $users = $users->where('name', 'LIKE', "%$find_key%")
                ->orWhere('surname', 'LIKE', "%$find_key%")
                ->orWhere('name_man', 'LIKE', "%$find_key%")
                ->orWhere('email', 'LIKE', "%$find_key%")
                ->orWhere('telephone', 'LIKE', "%$find_key%");
        }
        $count_users = $users->count();

        // Данные
        $users = $users
            ->Baseuser()
            ->orderByDesc('created_at')
            ->paginate(10);

        $export_options = DbExportColumns::toArray();

        $jobs_titles = Job_title::select('id', 'name')
            ->where('is_remove', '=', 0)
            ->where('is_bd', '=', 2)
            ->orderByDesc('sort')
            ->orderBy('name', 'asc')
            ->get()
            ->toArray()
        ;

        return view('employers.bd', compact('users', 'count_users', 'export_options', 'jobs_titles'));
    }

    //Настройка уведомлений
    public function subscribe() {

        $user=Auth::user();

        return view('employers.subcribe',compact('user'));
    }

    //Установка уведомлений сохранение
    public function save_subscribe(Request $request) {

        $msg = $request->validate([
          'email' => 'required|email|min:5|max:255',
      ]);
        $user= Auth::user();

        User_Model::updateOrCreate(
            ['id' => $user->id],
            ['subscribe_email' => $request->email,
                'subscribe' => request()->has('email_msg') && request('email_msg') === 'on' ? 1 : 0
            ]
        );
        return redirect()->route('employer.subscribe')->with('success', 'Ваши изменения успешно сохранены');
    }
    //Сбросить форму с паролем
    public function password_reset() {
        $email = Auth()->user()->email;
        return view('employers.password-reset', compact('email'));
    }

    //Обновление пароля
    public function 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('employer.password_reset')
                            ->with('success', 'Поздравляю! Вы обновили свой пароль!');
                    }

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

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



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

    // Удаление аккаунта
    public function action_delete_user(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('employer.delete_people')
                ->withErrors( 'Неверный пароль! Нужен корректный пароль');
        }
    }

    public function ajax_delete_user(Request $request) {
        $Answer = $request->all();
        $user_id = Auth()->user()->id;
        $request->validate([
            'password' => 'required|string',
        ]);
        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {

            return json_encode(Array('SUCCESS' => 'Вы успешно удалили свой аккаунт',
                                     'email' => $request->get('email'),
                                     'password' => $request->get('password')));
        } else {
            return json_encode(Array('ERROR' => 'Неверный пароль! Нужен корректный пароль'));
        }
    }

    // Рассылка сообщений
    public function send_all_messages() {
        $id = Auth()->user()->id;
        $sending = Employer::query()->where('user_id', '=', "$id")->first();

        $job_titles = Job_title::query()
            ->where('is_remove', '=', 0)
            ->where('is_bd', '=', 1)
            ->orderByDesc('sort')
            ->get();

        if ($sending->sending_is)
            return view('employers.send_all', compact('job_titles'));
        else
            return view('employers.send_all_danger');
    }

    // Отправка сообщений для информации
    public function send_all_post(Request $request) {
        $data = $request->all();
        $data['user'] = Auth()->user();

        $id = MessagesRequests::create([
            'user_id' => $data['user']->id,
            'job_titles' => isset($data['job_title_ids']) ? json_encode($data['job_title_ids']) : null,
            'text' => $data['message_text'],
        ]);

        try {
            if (!empty($id)) {
                Mail::to(env('EMAIL_ADMIN'))->send(new MassSendingMessages($data));
            }
        } catch (Throwable $e) {
            Log::error($e);
            return redirect()->route('employer.send_all_messages')->with('error', 'Ошибка почтового сервера, пожалуйста, повторите рассылку позднее');
        }

        return redirect()->route('employer.send_all_messages')->with('success', 'Запрос на рассылку был успешно отправлен.');
    }

    // База резюме
    public function bd_tupe(Request $request) {
        $Resume = User_Model::query()->with('workers')->where('is_bd', '=', '1')->get();

        return view('employers.bd_tupe', compact('Resume'));
    }

    //////////////////////////////////////////////////////////////////
    // Отправил сообщение
    //////////////////////////////////////////////////////////////////
    public function new_message(Request $request)
    {
        $params = $request->all();

        $id = $params['_user_id'];
        $message_params = [
            'title' => $params['title'],
            'text' => $params['text'],
            'ad_employer_id' => $params['_vacancy'],
            'flag_new' => 1
        ];

        $message = Message::add_message(
            $request,
            $params['_user_id'],
            $params['_to_user_id'],
            $message_params,
            file_store_path: "worker/$id"
        );

        return redirect()->route('employer.dialog', ['chat' => $message->chat_id_to]);
    }

    // Восстановление пароля
    public function repair_password(Request $request) {
        $params = $request->get('email');
    }

    // Избранные люди на корабль
    public function selected_people(Request $request) {
        $id = $request->get('id');
        $favorite_people = Job_title::query()->orderByDesc('sort')->OrderBy('name')->
            where('is_remove', '=', '0')->
            where('is_bd', '=', '0')->
            where('position_id', $id)->
            get();
        return view('favorite_people', compact('favorite_people'));
    }

    /**
     * @throws JsonException
     */
    public function vacancyAutoLiftForm(): View|RedirectResponse
    {
        if (!Auth::user()->can_autolift) {
            return redirect()->route('employer.employer_info');
        }

        $employer = Auth::user()->employers[0];
        $vacancies = $employer
            ->ads()
            ->where('is_remove', 0)
            ->where('active_is', 1)
            ->get();

        $options = $employer->autoliftOptions ?? new EmployerAutoliftOption();

        $leftDays = 0;

        if ($options->days_repeat) {
            $leftDays = $options->days_repeat - now()->diffInDays(Carbon::parse($options->created_at));
        }


        return view('employers.vacancy_autolift', compact('vacancies', 'options', 'leftDays'));
    }

    /**
     * @throws JsonException
     */
    public function vacancyAutoLiftSave(Request $request)
    {
        $employer = Auth::user()->employers[0];

        $employer->autoliftOptions()->updateOrCreate(
            [
                'employer_id' => $employer->id,
            ],
            [
                'is_enabled' => $request->get('is_enabled') === 'true',
                'times_per_day' => $request->get('times_per_day'),
                'days_repeat' => $request->get('days_repeat'),
                'time_send_first' => $request->get('time_send_first'),
                'time_send_second' => $request->get('time_send_second'),
                'time_send_third' => $request->get('time_send_third'),
                'time_send_tg' => $request->get('time_send_tg'),
            ]
        );

        foreach ($request->get('vacancies') as $vacancy) {
            Ad_employer::query()
                ->where('id', $vacancy['id'])
                ->update([
                    'autolift_site' => $vacancy['autolift_site'] === 'true', //they're arriving as strings
                    'autosend_tg' => $vacancy['autosend_tg'] === 'true',
                ]);
        }

        return response(['success' => true]);
    }

    public function autoresponder()
    {
        $user = Auth::user();
        return view('employers.autoresponder', compact('user'));
    }

    public function autoresponderSave(Request $request): RedirectResponse
    {
        $user = Auth::user();
        $user->autoresponder = $request->get('autoresponder', false) === 'on';
        $user->autoresponder_message = $request->get('autoresponder_message');
        $user->save();

        return redirect(route('employer.autoresponder'));
    }
}