<?php

namespace App\Livewire\Admin;

use Livewire\Component;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use App\Helpers\CMail;
use App\Models\UserSocialLink;

class Profile extends Component
{

    public $tab = null;
    public $tabname = "personal_details";
    protected $queryString = ['tab' => ['keep' => true]];

    public $name, $email, $username, $bio;
    public $current_password, $new_password, $new_password_confirmation;
    public $facebook_url, $instagram_url, $youtube_url, $linkedin_url, $twitter_url, $github_url;

    protected $listeners = [
        'updateProfile' => '$refresh'
    ];

    public function selectTab($tab) {
        $this->tab = $tab;
    }

    public function mount() {
        $this->tab = Request("tab") ? Request("tab") : $this->tabname;

        $user = User::with("social_links")->findOrFail(auth()->id());
        $this->name = $user->name;
        $this->email = $user->email;
        $this->username = $user->username;
        $this->bio = $user->bio;

        if(!is_null($user->social_links)) {
            $this->facebook_url = $user->social_links->facebook_url;
            $this->instagram_url = $user->social_links->instagram_url;
            $this->youtube_url = $user->social_links->youtube_url;
            $this->twitter_url = $user->social_links->twitter_url;
            $this->github_url = $user->social_links->github_url;
            $this->linkedin_url = $user->social_links->linkedin_url;
        }
    }

    public function updatePersonalDetails() {
        $user = User::findOrFail(auth()->id());

        $this->validate([
            "name" => "required",
            "username" => "required|unique:users,username,".$user->id,
        ], [
            "name.required" => "Name wird benötigt",
            "username.required" => "Benutzername wird benötigt",
            "username.unique" => "Benutzername bereits vergeben",
        ]);

        $user->name = $this->name;
        $user->username = $this->username;
        $user->bio = $this->bio;
        $updated = $user->save();

        sleep(0.5);

        if($updated) {
            $this->dispatch("showToastr", ["type" => "success", "message" => "Deine Profil Informationen wurden bearbeitet"]);
            $this->dispatch("updateTopUserInfo")->to(TopUserInfo::class);
        } else {
            $this->dispatch("showToastr", ["type" => "error", "message" => "Deine Profil Informationen konnten nicht bearbeitet werden"]);
        }
    }

    public function updatePassword(Request $request) {
        $user = User::findOrFail(auth()->id());

        $this->validate([
            "current_password" => [
                "required",
                "min:5",
                function($attribute, $value, $fail) use ($user) {
                    if(!Hash::check($value, $user->password)) {
                        return $fail(__('Dein Passwort stimmt nicht überein'));
                    }
                }
            ],
            "new_password" => "required|min:5|confirmed"
        ], [
            "current_password.required" => "Das aktuelle Passwort wird benötigt",
            "current_password.min" => "Gebe mind. 5 Zeichen ein",
            "new_password.required" => "Das aktuelle Passwort wird benötigt",
            "new_password.min" => "Gebe mind. 5 Zeichen ein",
        ]);

        $updated = $user->update([
            "password" => Hash::make($this->new_password)
        ]);

        if($updated) {
            $data = array(
                "user" => $user,
                "new_password" => $this->new_password
            );

            $mail_body = view("email-templates.password-changes-template", $data)->render();

            $mail_config = array(
                'recipient_address' => $user->email,
                'recipient_name' => $user->name,
                "subject" => "Passwort geändert",
                "body" => $mail_body
            );

            CMail::send($mail_config);
            auth()->logout();
            Session::flash("info", "Dein Passwort wurde geändert, bitte logge dich neu ein");
            $this->redirectRoute("admin.login");
        } else {
            $this->dispatch("showToastr", ["type" => "error", "message" => "Leider lief etwas schief"]);
        }
    }

    public function updateSocialLinks() {
        $this->validate([
            'facebook_url' => 'nullable|url',
            'instagram_url' => 'nullable|url',
            'youtube_url' => 'nullable|url',
            'linkedin_url' => 'nullable|url',
            'twitter_url' => 'nullable|url',
            'github_url' => 'nullable|url',
        ],[
            'facebook_url.url' => "Du musst einen gültigen Link angeben",
            'instagram_url.url' => "Du musst einen gültigen Link angeben",
            'youtube_url.url' => "Du musst einen gültigen Link angeben",
            'linkedin_url.url' => "Du musst einen gültigen Link angeben",
            'twitter_url.url' => "Du musst einen gültigen Link angeben",
            'github_url.url' => "Du musst einen gültigen Link angeben",
        ]);

        $user = User::findOrFail(auth()->id());

        $data = array(
            'instagram_url' => $this->instagram_url,
            'facebook_url' => $this->facebook_url,
            'youtube_url' => $this->youtube_url,
            'linkedin_url' => $this->linkedin_url,
            'twitter_url' => $this->twitter_url,
            'github_url' => $this->github_url,
        );

        if(!is_null($user->social_links)) {
            $query = $user->social_links()->update($data);
        } else {
            $data['user_id'] = $user->id;
            $query = UserSocialLink::insert($data);
        }

        if($query) {
            $this->dispatch("showToastr", ["type" => "success", "message"=> "Social Links erfolgreich bearbeitet"]);
        } else {
            $this->dispatch("showToastr", ["type" => "error", "message"=> "Fehler beim bearbeiten von Social Links"]);
        }
    }

    public function render()
    {
        return view('livewire.admin.profile', [
            "user" => User::findOrFail(auth()->id())
        ]);
    }
}
