<?php

namespace App\Services;

use Exception;
use Illuminate\Support\Str;
use App\Models\Organization;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use App\Mails\ChangePasswordConfirmMail;
use Illuminate\Validation\ValidationException;

class ProfileService
{
    public function changePassword($currentpassword, $newpassword, $hashedcurrentpassword)
    {
        // check security question exists before change password
        $this->checkSecurityQuestionExists();

        if (!Hash::check($currentpassword, $hashedcurrentpassword)) {
            return $this->sendFailedResponse('passwords.current_password_not_correct');
        }

        if (Hash::check($newpassword, $hashedcurrentpassword)) {
            return $this->sendFailedResponse('passwords.new_and_old_password_the_same');
        }

        auth()->user()->update([
            'Password' => Hash::make($newpassword)
        ]);

        try {
            (new ChangePasswordConfirmMail(auth()->user()))->send();
        } catch (Exception $e) {
            return $this->sendFailedResponse('passwords.password_changed_but_smtp_error');
        }

        return $this->CurrentPasswordUpdatedSuccessfully();
    }

    private function sendFailedResponse($response)
    {
        return response()->json([
            'message' => 'failed',
            'errors'  => [
                'password' => [trans($response)]
            ]
        ], 419);
    }

    private function CurrentPasswordUpdatedSuccessfully()
    {
        return response()->json([
            'message' => trans('passwords.updated')
        ]);
    }

    public function updateOrganizationDetails($data)
    {

        $organization_details = Organization::first();

        if ($organization_details) {
            $organization_details->update($data);
        } else {
            Organization::create($data);
        }

    }

    public function storeOrganizationLogo($logo)
    {
        $organization = Organization::first();

        if ($organization && $logo) {
            $imageName          = Str::uuid() . '.' . $logo->getClientOriginalExtension();
            $path               = $logo->storeAs('logos', $imageName, 'public');
            $organization->logo = $path;
            $organization->save();
        }

    }

    public function removeOrganizationLogo()
    {
        $organization = Organization::first();

        if ($organization) {
            Storage::disk('public')->delete($organization->logo);
            $organization->logo = null;
            $organization->save();
        }

    }

    private function checkSecurityQuestionExists()
    {

        if (empty(auth()->user()->Security_answer)) {
            throw ValidationException::withMessages([
                'currentpassword' => trans('profile.security_question_messing')
            ]);
        }

    }

}
