<?php

namespace App\Http\Controllers\nn_site;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\nn_category;
use App\Models\nn_site_users;
use App\Models\nn_company;
use App\Models\nn_company_lang;
use App\Models\nn_company_category;
use App\Models\nn_job;
use App\Models\nn_job_lang;
use App\Models\nn_job_category;
use Illuminate\Support\Facades\Hash;
use LaravelLocalization;

class SiteCompanyUserProfileController extends SiteController
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function index(Request $request)
    {
        $companyId = $request->session()->get('company_user')['company_id'];

        $data['items'] = nn_job::join('nn_job_lang', 'nn_job_lang.job_id', '=', 'nn_job.id')
                        ->with([
                            'categories' => function ($q) {
                                $q->join('nn_category_lang', 'nn_category_lang.category_id', '=', 'nn_job_category.category_id')
                                ->where('nn_category_lang.lang', getCurrentLocale())
                                ->orderBy('nn_category_lang.created_at', 'desc');
                            }
                        ])
                        ->join('nn_job_category', 'nn_job_category.job_id', '=', 'nn_job.id')
                        ->select(
                                'nn_job.id',
                                'nn_job.created_at',
                                'nn_job.end_date',
                                'nn_job_lang.name'
                            )
                        ->where([['nn_job.company_id', $companyId], ['nn_job_lang.lang', getCurrentLocale()]])
                        ->orderBy('nn_job.created_at', 'desc')
                        ->groupBy('nn_job.id')
                        ->limit(3)
                        ->get();

        return view('nn_site.pages.company_profile.pages.home', $data);
    }
    
    public function editUserForm()
    {
        return view('nn_site.pages.company_profile.pages.edit_user');
    }
    
    public function updateUser(Request $request)
    {
        $userId = $request->session()->get('company_user')['id'];

        $validationData = [
            'firstname' => 'required',
            'lastname' => 'required',
            'phone' => 'required',
            'personal_id' => 'required|max:11|min:11',
        ];
        
        if ($request->get('password') != '') {

            $validationData['password'] = 'required|confirmed|min:6';

        }

        $validated = $request->validate($validationData);

        $user = nn_site_users::find($userId);
        $user->firstname = $request->firstname;
        $user->lastname = $request->lastname;
        $user->personal_id = $request->personal_id;
        $user->phone = $request->phone;
        $user->address = $request->address;

        if ($request->get('password') != '') {
            $user->password = Hash::make($request->password);
        }

        $user->save();

        return redirect('/'.getCurrentLocale().'/company/user/edit');
    }

    public function editCompanyForm(Request $request)
    {
        $userId = $request->session()->get('company_user')['id'];

        $data['company'] = nn_company::where('user_id', $userId)->first();
        $companyLang = nn_company_lang::where('company_id', $data['company']->id)->get();
        $data['companyCategories'] = nn_company_category::where('company_id', $data['company']->id)->select('category_id')->get();

        foreach ($companyLang as $item) {
            $data['companyLang']['name_' . $item->lang] = $item->name;
            $data['companyLang']['address_' . $item->lang] = $item->address;
            $data['companyLang']['description_' . $item->lang] = $item->description;
        }

        $data['categories'] = nn_category::getCategory();

        return view('nn_site.pages.company_profile.pages.edit_company', $data);
    }

    public function updateCompany(Request $request)
    {
        $userId = $request->session()->get('company_user')['id'];

        $validationData = [
            'name_ka' => 'required',
            'name_en' => 'required',
            'name_ru' => 'required',
            'code' => 'required',
            'category_id' => 'required',
        ];

        $validated = $request->validate($validationData);

        $company = nn_company::where('user_id', $userId)->first();
        $company->code = $request->code;
        $company->country_id = $request->country_id;
        $company->min_budget = $request->min_budget;
        $company->min_hour = $request->min_hour;
        $company->creation_date = $request->creation_date;
        $company->number_of_staff = $request->number_of_staff;

        if ($request->hasFile('cover')) {
            if ($request->file('cover')->isValid()) {
    
                $validated = $request->validate([
                    'cover' => 'mimes:jpeg,png|max:3000',
                ]);
    
                $extension = $request->cover->extension();
                $fileName = $userId.'_cover.'.$extension;
                $request->file('cover')->move(public_path('assets/nn_site/uploads/company'), $fileName);
    
            }

            $company->cover = $fileName;
        }
        if ($request->hasFile('logo')) {
            if ($request->file('logo')->isValid()) {
    
                $validated = $request->validate([
                    'logo' => 'mimes:jpeg,png|max:3000',
                ]);

                $extension = $request->logo->extension();
                $fileName = $userId.'_logo.'.$extension;
                $request->file('logo')->move(public_path('assets/nn_site/uploads/company'), $fileName);
    
            }

            $company->logo = $fileName;
        }

        $company->save();

        nn_company_category::where('company_id', $company->id)->delete();

        $categoryIds = $request->get('category_id');

        foreach ($categoryIds as $item) {

            $companyCategory = new nn_company_category();

            $companyCategory->company_id = $company->id;
            $companyCategory->category_id = $item;

            $companyCategory->save();

        }

        foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties) {

            $companyLang = nn_company_lang::where([['company_id', $company->id], ['lang', $localeCode]])->first();

            $companyLang->name = $request->get('name_'.$localeCode);
            $companyLang->address = $request->get('address_'.$localeCode);
            $companyLang->description = $request->get('description_'.$localeCode);

            $companyLang->save();

        }

        return redirect('/'.getCurrentLocale().'/company/edit');
    }
    
    public function addJobForm(Request $request)
    {
        $userId = $request->session()->get('company_user')['id'];
        $companyId = $request->session()->get('company_user')['company_id'];

        $data['categories'] = nn_company_category::where([
                ['company_id', $companyId],
                ['nn_category_lang.lang', getCurrentLocale()]
            ])
            ->join('nn_category_lang', 'nn_category_lang.category_id', 'nn_company_category.category_id')
            ->select(\DB::raw('nn_category_lang.category_id AS id'), 'nn_category_lang.name')->get();

        return view('nn_site.pages.company_profile.pages.add_job', $data);
    }
    
    public function storeJob(Request $request)
    {
        $companyId = $request->session()->get('company_user')['company_id'];

        $validationData = [
            'name' => 'required',
            'end_date' => 'required',
            'budget' => 'required',
            'category_id' => 'required',
        ];

        $validated = $request->validate($validationData);

        $job = new nn_job();
        $job->end_date = $request->end_date;
        $job->budget = $request->budget;
        $job->company_id = $companyId;

        $job->save();

        $categoryIds = $request->get('category_id');

        foreach ($categoryIds as $item) {

            $jobCategory = new nn_job_category();

            $jobCategory->job_id = $job->id;
            $jobCategory->category_id = $item;

            $jobCategory->save();

        }

        foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties) {

            $jobLang = new nn_job_lang();

            $jobLang->name = $request->get('name');
            $jobLang->description = $request->get('description');
            $jobLang->lang = $localeCode;
            $jobLang->job_id = $job->id;

            $jobLang->save();

        }

        return redirect('/'.getCurrentLocale().'/company/profile');
    }
}
