<?php

namespace Modules\Admin\Controllers;

use App\Controllers\Auth\AuthController;


class Dashboard extends AuthController
{
    public function initController($request, $response, $logger)
    {
        parent::initController($request, $response, $logger);
    }

  public function index()
  {		
    // display header information
		$this->data['title'] = "Dashboard";
        $this->data['bcrumb'] = "Dashboard";

        if (!$this->session->get('loggedIn'))
        {
            return redirect()
                ->to('login');
        }
        $this->data['notifications'] = $this->notificationsModel->where('receiver_id', $this->userdata->user_id)->orderBy('id', 'DESC')->findAll(5);
        $this->data['popular_posts'] = $this->postsModel->getPopularPosts();
        $this->data['new_posts'] = $this->postsModel->getLatestPosts();
        $this->data['countPages'] = count($this->postsModel->getAllPages()); //Count all pages
        $this->data['countPosts'] = count($this->postsModel->getAllSitePosts()); //count all posts
        $this->data['countDownloads'] = count($this->downloadsModel->getAll()); //count Downloads
        $this->data['allHits'] = $this->webtrafficModel->getTotalHits();//Total Hits - No page specific

		return view('Modules\Admin\Views\dashboard\dashboard', $this->data);
  }

  //Display User Profile
  public function userProfile()
  {
      //Page title & Path
      $this->data['title'] = $this->userdata->first_name.' '.$this->userdata->last_name.' Profile';
      $this->data['bcrumb'] =  $this->userdata->first_name.' Profile';

      $this->data['single'] = $this->usersModel->singleUser($this->userdata->user_id);

      return View('Modules\Admin\Views\dashboard\users_profile', $this->data);
  }

  public function updateUserProfile()
  {
        //Page title & Path
        $this->data['title'] = $this->userdata->first_name.' '.$this->userdata->last_name.' Profile';
        $this->data['bcrumb'] =  $this->userdata->first_name.' Profile';
        $this->data['single'] = $this->usersModel->singleUser($this->userdata->user_id);

       $rules = [
            'first_name' => ['label' => 'Name', 'rules' => 'required'],
        ];
        $photoRules = [
            'photo' => [
                'label' => 'Image File',
                'rules' => 'uploaded[photo]'
                    . '|is_image[photo]'
                    . '|mime_in[photo,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
                    . '|max_size[photo,1024]'
            ],
        ];
        if($this->request->getMethod() == 'POST')
        {
            if($this->validate($rules))
            {
                $id = $this->request->getPost('id');
                //Profile Image is uploaded
                $file1 = $this->request->getFile('photo');
                if($file1 != "")
                {
                    if($this->validate($photoRules))
                    { 
                        $newName4 = $file1->getRandomName();
                        $file1->move(ROOTPATH . 'media/user/profiles', $newName4);
                        $nwn1 = base_url('/media/user/profiles/').'/'.$newName4;

                        $adminData = [
                            'photo'             => $nwn1,
                            'first_name'        => $this->request->getVar('first_name'),
                            'last_name'         => $this->request->getVar('last_name'),
                            'address'           => $this->request->getVar('address'),
                            'mobile'            => $this->request->getVar('mobile'),
                            'gender'            => $this->request->getVar('gender'),
                            'city_id'           => $this->request->getPost('city_id'),
                            'state_id'          => $this->request->getPost('state_id'),
                            'country_id'        => $this->request->getPost('country_id'),
                            'facebook'          => $this->request->getVar('facebook'),
                            'twitter'           => $this->request->getVar('twitter'),
                            'whatsapp'          => $this->request->getVar('whatsapp'),
                            'instagram'         => $this->request->getVar('instagram'),
                            'linkedin'          => $this->request->getVar('linkedin'),
                            'updated_at'        => date('Y-m-d H:i:s'),
                        ];
                        if($this->usersModel->update($id, $adminData))
                        {
                            session()->setFlashdata('success', 'Profile Updated Successfully');
                            return redirect()->to('administrator/my-profile');
                        }else
                        {
                            session()->setFlashdata('success', 'Profile not Updated');
                            return redirect()->to('administrator/my-profile');;
                        }
                    }else
                    {
                        $this->data['validation'] = $this->validator;
                    }
                }else
                {
                    $adminData = [
                        'first_name'        => $this->request->getVar('first_name'),
                        'last_name'         => $this->request->getVar('last_name'),
                        'address'           => $this->request->getVar('address'),
                        'mobile'            => $this->request->getVar('mobile'),
                        'gender'            => $this->request->getVar('gender'),
                        'city_id'           => $this->request->getPost('city_id'),
                        'state_id'          => $this->request->getPost('state_id'),
                        'country_id'        => $this->request->getPost('country_id'),
                        'facebook'          => $this->request->getVar('facebook'),
                        'twitter'           => $this->request->getVar('twitter'),
                        'whatsapp'          => $this->request->getVar('whatsapp'),
                        'instagram'         => $this->request->getVar('instagram'),
                        'linkedin'          => $this->request->getVar('linkedin'),
                        'updated_at'        => date('Y-m-d H:i:s'),
                    ];

                    if($this->usersModel->update($id, $adminData))
                        {
                            session()->setFlashdata('success', 'Profile Updated Successfully');
                            return redirect()->to('administrator/my-profile');
                        }else
                        {
                            $this->session->setFlashdata('success', 'Profile not Updated');
                            return redirect()->to('administrator/my-profile');
                        }
                }
            }else
            {
                $this->data['validation'] = $this->validator;
            }
        }
        
    
        return View('Modules\Admin\Views\dashboard\users_profile', $this->data);
    }
    public function updateUserPwd()
    {
        //Page title & Path
        $this->data['title']   = 'Password & Security';
        $this->data['bcrumb'] = 'Update Password';

        $this->data['single'] = $this->usersModel->singleUser($this->userdata->user_id);
        if($this->request->getMethod() == 'POST')
        {
            $rules = [
                'password' => ['label' => 'Password', 'rules' => 'required|min_length[8]|max_length[18]|alpha_numeric_punct'],
                'cpass'	=> ['label' => 'Confirm Password', 'rules' => 'required|min_length[8]|max_length[20]|matches[password]'],
            ];
            if($this->validate($rules))
            {
                $id = $this->request->getVar('user_id');
                $password = password_hash($this->request->getVar('password'), PASSWORD_DEFAULT);
                $newPwd = [
                    'password' => $password,
                ];
                if($this->usersModel->update($id, $newPwd))
                {
                    $adminmessage = 'User '.$this->userdata->email.' changed password';
                    $usermessage = 'Password updated successfully';
                    $notificationType = 'security';
                    $this->sendAdminNotifications($adminmessage, $notificationType, $id);
                    $this->sendUserNotifications($usermessage, $notificationType, $id); 
                    
                    session()->setFlashdata('success', 'Password updated successfully');
                    return redirect()->to('administrator/my-profile');
                    
                }else
                {
                      session()->setFlashdata('success', 'Password update failed');
                      return redirect()->to('administrator/my-profile');
                }
            }else{
              $this->data['validation'] = $this->validator;
            }
        }
        return View('Modules\Admin\Views\dashboard\users_profile', $this->data);
    }



}
