<?php
/*
 * Copyright (c) 2023.
 *
 * A.Сапаргалиев
 * ТОО "Дизайн лаборатория А7"
 * Астана
 */

namespace App\Modules\UserProfile\Applications;

use A7kz\Platform\Models\UniModel;
use A7kz\Platform\Modules\Platform\Acl\Facades\Acl;
use A7kz\Platform\Modules\Platform\Core\Services\Application\BaseApplication;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;

class UserProfileApplication extends BaseApplication
{
    public function __construct($config)
    {
        parent::__construct($config);
    }

    public function default()
    {
        return view('platform.user_profile::profile', ['user'=>Auth::user()])->render();
    }

    public function action_changecompany(){
        $isAdmin = false;

        if (Acl::isHasRole('admin')) {
            $isAdmin = true;
        }

        $company = UniModel::model('core_company_users')
            ->where("company_id", Request::get('pk'))
            ->where("user_id", Auth::id());
        $hasAccess = $company->count();

        if(!$isAdmin && !$hasAccess){
            return redirect($this->getPath());
        }
        UniModel::model('core_company_users')
            ->where("user_id", Auth::id())->update(['is_last_company' => false]);
        $company->update(['is_last_company' => true]);

        Request::session()->put('user.rights', Acl::getUserRights(Auth::id(),Request::get('pk')));
        Request::session()->put('user.company_id', Request::get('pk'));
        $organization = Accounting::organization(Acl::company_id());
        if(is_null($organization)){
            $company = Acl::activeCompany();
            $organization = UniModel::model("acc_organizations", Acl::connection());
            $organization->id = Acl::company_id();
            $organization->biniin = $company->biniin;
            $organization->name_ru = $company->name;
            $organization->name_kz = $company->name;
            $organization->code_gu = "0";
            $organization->fullname_ru = $company->fullname;
            $organization->fullname_kz = $company->fullname;
            $organization->taxation_id = 1;
            $organization->organization_type = 'OSH'; // Школа
            $organization->company_id = Acl::company_id();
            $organization->save();
        }
        $orgdata = [
            'name_kz' => $organization->name_kz ?? '',
            'name_ru' => $organization->name_ru ?? '',
            'biniin' => $organization->biniin ?? '',
            'calc_via_id' => $organization->calc_via_id ?? '',
            'code_gu' => $organization->code_gu ?? '',
            'organization_type' => $organization->organization_type ?? '',
        ];
        Request::session()->put('organization', $orgdata);
        Request::session()->reflash();
        Request::session()->put('user.grid_filters', []);
        Request::session()->put('user.tabs', null);

        return redirect($this->getPath());
    }

    public  function action_edit(){
        $user = Auth::user();
        $request = Request::all();

        if (Request::has('submit')) {
            $rules = [
                'name' => ['required', 'string', 'max:255'],
                'phone' => ['required', 'string', 'max:255'],
                'about' => ['nullable', 'string', 'max:255'],
                'email' => ['required', 'string', 'email', 'max:255'],
                'profile_image' => ['nullable', 'image', 'mimes:jpg,png,jpeg', 'max:2048']
            ];

            $validator = Validator::make(Request::all(), $rules);

            if ($validator->fails()) {
                $errors = $validator->errors();

                foreach ($rules as $field => $rule) {
                    if ($errors->has($field)) {
                        switch ($field) {
                            case 'name':
                                $this->set_message('Неправильно заполнено поле "Имя"', 'error');
                                break;
                            case 'phone':
                                $this->set_message('Неправильно заполнено поле "Телефон"', 'error');
                                break;
                            case 'about':
                                $this->set_message('Неправильно заполнено поле "О себе"', 'error');
                                break;
                            case 'profile_image':
                                $this->set_message('Неправильный формат картинки', 'error');
                                break;
                            case 'email':
                                $this->set_message('Неправильно заполнено поле "Почта"', 'error');
                                break;
                        }
                    }
                }
                return view('platform.user_profile::user_edit', [
                    'user' => Auth::user(),
                    'app' => $this
                ])->render();
            }

            $profile_image = '';
            if (Request::hasFile('profile_image')) {
                $imagePath = 'profile_images/' . auth()->user()->profile_image;
                if (File::exists($imagePath)) {
                    File::delete($imagePath);
                }
                $profile_image = $request['profile_image']->store('profile_images', 'public');
            }

            $user->name = $request['name'];
            $user->phone = $request['phone'];
            $user->about = $request['about'];
            $user->email = $request['email'];
            $user->profile_image = $profile_image ?? auth()->user()->profile_image;

            if (!empty($request['new_password'])) {
                if (!Hash::check($request['current_password'], $user->password)) {
                    $this->set_message('Неверный текущий пароль', 'error');
                    return view('platform.user_profile::user_edit', [
                        'user' => Auth::user(),
                        'app' => $this
                    ])->render();
                }
                $user->password = Hash::make($request['new_password']);
            }

            $user->save();
            $this->set_message('Данные сохранены', 'success', false);
        }
        return view('platform.user_profile::user_edit', [
            'user' => Auth::user(),
            'app' => $this
        ])->render();
    }
}
