<?php

namespace App\Livewire\Admin;

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

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;
    protected $listeners = [
        'updateProfile' => '$refresh'
    ];
    public function selectTab($tab)
    {  // Correct
        $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;
        }
    }

    public function updatePersonalDetails()
    {
        $user = User::findOrFail(Auth::id());
        $this->validate([
            'name' => 'required',
            'username' => 'required|unique:users,username,' . $user->id,
        ]);
        $user->name = $this->name;
        $user->username = $this->username;
        $user->bio = $this->bio;
        $update = $user->save();

        sleep(0.5);

        if ($update) {
            $this->dispatch('showToastr', type : 'success', message: 'Your personal details have been updated successfully.');
            $this->dispatch('updateTopUserInfo')->to(TopUserInfo::class);
        } else {
            $this->dispatch('showToastr', type : 'error', message: 'Something went wrong.');
        }
    }
    public function updatePassword()
    {
        $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(__('Your current password does not match our records.'));
                    }
                }
            ],
            'new_password' => 'required|min:5|confirmed'

        ]);

        $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-change-template', $data)->render();
            $mail_config = array(
                'recipient_address'=>$user->email,
                'recipient_name'=>$user->name,
                'subject'=>'Password Changed',
                'body'=>$mail_body
            );

            CMail::send($mail_config);
            Auth::logout();
            Session::flash('info', 'Your password has been successfully changed. Please login with your new password.');
            $this->redirectRoute('admin.login');
        }else{
            $this->dispatch('showToastr',type :'error', message : 'Something went wrong.');
        }
    }
    public function updateSocialLinks(){
        $this->validate([
            'facebook_url'=>'nullable|url',
            'instagram_url'=>'nullable|url'
        ]);

        $user = User::findOrFail(Auth::id());
        $data = array(
            'facebook_url'=>$this->facebook_url,
            'instagram_url'=>$this->instagram_url,
            
        );
        if( !is_null($user->social_links)){
            $query = $user->social_links()->update($data);
        }else{
            $data['user_id'] = $user->id;
            $query = UserSocialLinks::insert($data);
        }

        if($query){
            
            $this->dispatch('showToastr',type :'success', message : 'Your social links have been updated successfully.');
        }else{
            $this->dispatch('showToastr',type :'error', message : 'Something went wrong');
        }
    }
    public function render()
    {
        return view('livewire.admin.profile', [
            'user' => User::findOrFail(Auth::id())
        ]);
    }
}
