<?php 
namespace App\Controllers;
use App\Models\UserModel;
class Users extends BaseController
{
	
	public function userlist()
	{
		$session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     $this->response->redirect(site_url('/login'));
		  exit;
        }
		
		$data = [];
		$data = ['data' => ''];
		
		$db = db_connect();
	    $query = $db->query('SELECT * from users order by id desc');
	    $users=$query->getResult('array');
		$data['users']=$users;

		$query = $db->query('SELECT COUNT(*) as inactive_count FROM users WHERE active=0');
		$inactiveUsers = $query->getRowArray();
		$data['new_users'] = $inactiveUsers['inactive_count'];

		echo view('user/userlist', $data);
	}
	
	// Returns a list of all users with the specified role
	// Valid roles are "All", "New", "Admin", "Buyer", "Seller"
	public function getUsersByRole($role){
	
		if ($this->request->isAJAX() && session()->get('id') > 0) {

			// if (!in_array($role, ['All', 'New', 'Admin', 'Buyer', 'Seller'])) {
			// 	return $this->response->setStatusCode(400, 'Bad Request');
			// }

			$model = new UserModel();
			$users = $model->getUsersByRole($role);

			return $this->response->setJSON([
				'users' => $users,
				'count' => count($users)
			]);
		}
		return $this->response->setStatusCode(400, 'Bad Request');

	}
	public function edituser($id = -1) 
	{
        $session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     $this->response->redirect(site_url('/login'));
		  exit;
        }
		
		$data = [];
		$data = ['data' => ''];
		helper(['form']);
		$model = new UserModel();
		if ($this->request->getMethod() == 'POST') {
			$rules = [
				'email' => 'required|min_length[4]|max_length[50]',
				'phone' => 'required|min_length[4]|max_length[50]',
				'companyname' => 'required|min_length[4]|max_length[50]',
				'firstname' => 'required|min_length[1]|max_length[50]',
				'lastname' => 'required|min_length[1]|max_length[50]',
				];

			if($this->request->getPost('password') != ''){
				$rules['password'] = 'required|min_length[8]|max_length[255]';
				$rules['password_confirm'] = 'matches[password]';
			}
			if (! $this->validate($rules)) {
				$data['validation'] = $this->validator;
			}else{
				
				
				$hide_zadio=0;
				
				
				if($this->request->getVar('hide_zadio')=="on")
					$hide_zadio=1;
				
				
				if($this->request->getVar('active'))
					$active=1;
				else
					$active=0;
				
				if($this->request->getVar('readonly'))
					$readonly=1;
				else
					$readonly=0;
				
				$newData = [
					'id'=>$id,
					'companyname' => $this->request->getVar('companyname'),
					'vatnumber' => $this->request->getVar('vatnumber'),
					'country' => $this->request->getVar('country'),
					'district' => $this->request->getVar('district'),
					'city' => $this->request->getVar('city'),
					'address' => $this->request->getVar('address'),
					'firstname' => $this->request->getVar('firstname'),
					'lastname' => $this->request->getVar('lastname'),
					'email' => $this->request->getVar('email'),
					'website' => $this->request->getVar('website'),
					'phone' => $this->request->getVar('phone'),
					'contactemail' => $this->request->getVar('contactemail'),
					'commission_type'=> $this->request->getVar('coms'),
					'commission_abs'=> $this->request->getVar('commission_abs'),
					'commission_percent'=> $this->request->getVar('commission_percent')/100,
					'commission_min'=> $this->request->getVar('commission_min'),
					'hide_zadio'=> $hide_zadio,
					'access' => $this->request->getPost('access')
					
				];
				//var_dump($newData);exit;
				if($this->request->getPost('password') != ''){
					$newData['password'] = $this->request->getPost('password');
				}
				$sendMail=false;
				// Check if the user already exists
				$user = $model->where('id', $id)->first();
				// Check if we are supposed to send an activation email
				if ($user && $user['active'] == 0 && $user['access'] != $newData['access']) {
					$sendMail = true;
					$newData['active'] = 1;
				}


				$model->save($newData);

				if ($sendMail) {
				$msg = view('emails/account_validation_email_user');
				// Send email to user
				$email = service('email');
				$email->setTo($this->request->getVar('email'));
				$email->setSubject('Your ZadioCars account');
				$email->setMessage($msg);
				$email->send();
				}
				session()->setFlashdata('success', 'Company data successfuly updated');
				return redirect()->to('/userlist');
			}
		}
		$data['user'] = $model->where('id', $id)->first();
		return view('user/edituser', $data);
        	
    }
	
	
	public function viewuser($id = -1) 
	{
        $session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     $this->response->redirect(site_url('/login'));
		  exit;
        }
		
		$data = [];
		$data = ['data' => ''];
		helper(['form']);
		$model = new UserModel();
		if ($this->request->getMethod() == 'POST') {
			$rules = [
				'email' => 'required|min_length[4]|max_length[50]',
				'phone' => 'required|min_length[4]|max_length[50]',
				'companyname' => 'required|min_length[4]|max_length[50]',
				'firstname' => 'required|min_length[1]|max_length[50]',
				'lastname' => 'required|min_length[1]|max_length[50]',
				];

			if($this->request->getPost('password') != ''){
				$rules['password'] = 'required|min_length[8]|max_length[255]';
				$rules['password_confirm'] = 'matches[password]';
			}
			if (! $this->validate($rules)) {
				$data['validation'] = $this->validator;
			}else{
				
				
				
				if($this->request->getVar('active'))
					$active=1;
				else
					$active=0;
				
				if($this->request->getVar('readonly'))
					$readonly=1;
				else
					$readonly=0;
				
				$newData = [
					'id'=>$id,
					'companyname' => $this->request->getVar('companyname'),
					'vatnumber' => $this->request->getVar('vatnumber'),
					'country' => $this->request->getVar('country'),
					'district' => $this->request->getVar('district'),
					'city' => $this->request->getVar('city'),
					'address' => $this->request->getVar('address'),
					'firstname' => $this->request->getVar('firstname'),
					'lastname' => $this->request->getVar('lastname'),
					'email' => $this->request->getVar('email'),
					'website' => $this->request->getVar('website'),
					'phone' => $this->request->getVar('phone'),
					'contactemail' => $this->request->getVar('contactemail'),
					'commission_type'=> $this->request->getVar('coms'),
					'commission_abs'=> $this->request->getVar('commission_abs'),
					'commission_percent'=> $this->request->getVar('commission_percent')/100,
					'commission_min'=> $this->request->getVar('commission_min'),
					'hide_zadio'=> $hide_zadio
					
					
				];
				//var_dump($newData);exit;
				if($this->request->getPost('password') != ''){
					$newData['password'] = $this->request->getPost('password');
				}
				$model->save($newData);
				session()->setFlashdata('success', 'Company data successfuly updated');
				return redirect()->to('/userlist');
			}
		}
		$data['user'] = $model->where('id', $id)->first();
		return view('user/viewuser', $data);
        	
    }
	
	
	private function setUserSession($user){
		$data = [
			'id' => $user['id'],
			'companyname' => $user['companyname'],
			'username' => $user['email'],
			'firstname' => $user['firstname'],
			'lastname' => $user['lastname'],
			'email' => $user['email'],
			'buyer' => $user['buyer'],
			'seller' => $user['seller'],
			'isAdmin' => true,
			'isLoggedIn' => true,
		];
		session()->set($data);
		return true;
	}
	
	
	
	public function login()
	{
		$data = [];
		$data = ['data' => ''];
		helper(['form']);
		if ($this->request->getMethod() == 'POST') {
			$rules = [
				'email' => 'required|min_length[3]|max_length[100]',
				'password' => 'required|min_length[8]|max_length[255]|validateUser[username,password]',
			];
			$errors = [
				'password' => [
					'validateUser' => 'Email or Password don\'t match'
				]
			];
			if (! $this->validate($rules, $errors)) {
				$data['validation'] = $this->validator;
			}else{
				$model = new UserModel();
				$user = $model->where('email', $this->request->getVar('email'))->first();
				$this->setUserSession($user);
				return redirect()->to('dashboard');
			}
		}
		return view('user/login', $data);
	}
	
	public function __register(){
		$libpath=realpath(dirname(__DIR__) . '/..');
		include_once $libpath.'/send_smtp.php';
		//sendMyMsg('edi.hermann@lemonbyte.ro','edi.hermann@lemonbyte.ro','New registration in cars@zadio.bg','zzzzzzzzzz');
				
		$data = [];
		helper(['form']);
		
		if ($this->request->getMethod() == 'POST') {
			
			$rules = [
				'companyname' => 'required|min_length[3]|max_length[50]',
				'vatnumber' => 'required|min_length[1]|max_length[50]',
				'country' => 'required|min_length[1]|max_length[50]',
				'district' => 'required|min_length[1]|max_length[50]',
				'city' => 'required|min_length[1]|max_length[50]',
				'address' => 'required|min_length[1]|max_length[200]',
				'firstname' => 'required|min_length[1]|max_length[20]',
				'lastname' => 'required|min_length[1]|max_length[20]',
				'email' => 'required|min_length[6]|max_length[50]|valid_email|is_unique[users.email]',
				'password' => 'required|min_length[8]|max_length[255]',
				'password_confirm' => 'matches[password]',
				
			];

			if (! $this->validate($rules)) {
				$data['validation'] = $this->validator;
			}else{
				$model = new UserModel();
				if($this->request->getVar('buyer'))
					$buyer=1;
				else
					$buyer=0;
				
				if($this->request->getVar('seller'))
					$seller=1;
				else
					$seller=0;
				
				
				$newData = [
					
					'companyname' => $this->request->getVar('companyname'),
					'vatnumber' => $this->request->getVar('vatnumber'),
					'country' => $this->request->getVar('country'),
					'district' => $this->request->getVar('district'),
					'city' => $this->request->getVar('city'),
					'address' => $this->request->getVar('address'),
					'firstname' => $this->request->getVar('firstname'),
					'lastname' => $this->request->getVar('lastname'),
					'email' => $this->request->getVar('email'),
					'phone' => $this->request->getVar('phone'),
					'password' => $this->request->getVar('password'),
					'buyer' => $buyer,
					'seller' => $seller,
				];
				$model->save($newData);
				$session = session();
				$session->setFlashdata('success', 'Successful Registration');
				
				$msg='Company:'.$this->request->getVar('companyname').'<br>';
				$msg.='Email:'.$this->request->getVar('email').'<br>';
				$msg.='Phone:'.$this->request->getVar('phone').'<br>';
				sendMyMsg('cars@zadio.bg','cars@zadio.bg','New registration in cars@zadio.bg',$msg);
				return redirect()->to('/users/confirmreg');

			}
		}
		return view('user/register', $data);
	}
	
	public function confirmreg()
	{
		$data = [];
		$data = ['data' => ''];
		
		return view('user/confirmreg', $data);
	}
	
	
	public function profile(){
		
		$session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     $this->response->redirect(site_url('/login'));
		  exit;
        }
		$data = [];
		$data = ['data' => ''];
		helper(['form']);
		$model = new UserModel();
		
		$session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     $this->response->redirect(site_url('/login'));
		  exit;
        }
		
		if ($this->request->getMethod() == 'POST') {
			$rules = [
				'firstname' => 'required|min_length[1]|max_length[20]',
				'lastname' => 'required|min_length[1]|max_length[20]',
				];

			
			if (! $this->validate($rules)) {
				$data['validation'] = $this->validator;
			}else{
				$newData = [
					'id' => session()->get('id'),
					'firstname' => $this->request->getPost('firstname'),
					'lastname' => $this->request->getPost('lastname'),
					'phone' => $this->request->getPost('phone'),
					
					];
					
				$model->save($newData);
				session()->setFlashdata('success', 'Company data successfuly updated');
				return redirect()->to('/dashboard');
			}
		}
		$data['user'] = $model->where('id', session()->get('id'))->first();
		
		return view('user/profile', $data);
	}
	
	public function changepwd(){
		$session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     $this->response->redirect(site_url('/login'));
		  exit;
        }
		
		$data = [];
		$data = ['data' => ''];
		$session = session();
		$usr = session()->get('id');
        if (!$usr>0) 
		{
	     $this->response->redirect(site_url('/login'));
		  exit;
        }
		
		helper(['form']);
		$model = new UserModel();
		if ($this->request->getMethod() == 'POST') {
			$rules = [];

			if($this->request->getPost('password') != ''){
				$rules['password'] = 'required|min_length[8]|max_length[255]';
				$rules['password_confirm'] = 'matches[password]';
			}
			if (! $this->validate($rules)) {
				$data['validation'] = $this->validator;
			}
			else{
				$newData = [
					'id'=>$usr,
					'password' => $this->request->getPost('password')
					];
					$model->save($newData);
					session()->setFlashdata('success', 'Password successfuly updated');
					return redirect()->to('/dashboard');
			}
		}
		$data['user'] = $model->where('id', session()->get('id'))->first();
		return view('user/changepwd', $data);
	}
	
	public function logout(){
		session()->destroy();
		return redirect()->to('/');
	}
}
