<?php

namespace App\Controllers\Admin;
use App\Models\UserModel;
use App\Models\LicenseModel;
use App\Controllers\BaseController;
class CreateLicenseController extends BaseController
{
    protected $session;
    public function __construct(){
        helper(['form']);
        $this->session = service('session');
    }
    public function index()
    {

        $userModel = new UserModel();
        $licenseModel = new LicenseModel();
        //$user = $userModel->where('Id', $seg1)->findAll();

        $data['title'] = 'Edit User';
        $data['msg'] = $this->session->getFlashdata('msg');
        $data['error'] = $this->session->getFlashdata('error');
        $data['users'] = (array) $userModel->findAll();
        $this->smartyView('admin/createlicense', $data);
    }

   
   public function is_unique($table,$value)
    {
        $userModel = new UserModel();
        $user = $userModel->where($table, $value)->findAll();
        if(!empty($user[0])){
            return TRUE;
        }else {
            return FALSE;
        }
    }
   public function is_unique_license($table,$value)
    {
        $licenseModel = new LicenseModel();
        $license = $licenseModel->where($table, $value)->findAll();
        if(!empty($license[0])){
            return TRUE;
        }else {
            return FALSE;
        }
    }
    public function store()
    {
        helper(['form']);

        $userModel = new UserModel();
        $licenseModel = new LicenseModel();
        $check = $userModel->where('Name', $this->request->getVar('username'))->findAll();
        /*$builder = $this->db->query("SELECT * FROM License WHERE ProductId={$this->request->getVar('plan')} AND UserID={$check[0]['Id']}");
        $checkLicense =  $builder->getRow();*/
         $rules = [
            'username' => [
                    'label'  => 'Usuario',
                    'rules'  => 'required|min_length[5]|max_length[20]',
                    'errors' => [
                    'required' => 'Seu {field} nao pode ser vazio',
                    'min_length' => '{field} deve ter no mino 5 letras ou numeros',
                    'max_length' => '{field} deve ter no maximo 20 letras ou numeros'
                ]
            ],
            'ip' => [
                    'label'  => 'MachineIP',
                    'rules'  => 'required|min_length[5]|max_length[50]',
                    'errors' => [
                    'required' => 'Seu {field} nao pode ser vazio',
                    'min_length' => '{field} deve ter no mino 5 letras ou numeros',
                    'max_length' => '{field} deve ter no maximo 20 letras ou numeros'
                ]
            ],
            'hdid' => [
                    'label'  => 'HarwareID',
                    'rules'  => 'required|min_length[5]|max_length[50]',
                    'errors' => [
                    'required' => 'Seu {field} nao pode ser vazio',
                    'min_length' => '{field} deve ter no mino 5 letras ou numeros',
                    'max_length' => '{field} deve ter no maximo 50 letras ou numeros'
                ]
            ],
            'plan' => [
                    'label'  => 'Senha',
                    'rules'  => 'required',
                    'errors' => [
                    'required' => 'Sua {field} nao pode ser vazio'
                ]
            ],

        ];


        if($this->validate($rules)){

        if(!$this->is_unique('Name', $this->request->getVar('username'))){
            return redirect()->to('/admin/addlicense')->with('msg', 'Usuario Nao Existe.'); 

        }
        
        /*elseif(isset($checkLicense)){
            return redirect()->to('/admin/addlicense')->with('msg', 'Este Usuario já uma uma licensa nesta versão.'); 
        }*/
        
        elseif($this->is_unique('Name', $this->request->getVar('username'))){

            $days = $this->request->getVar('days');

            $bonus = strtotime("+{$days} day");
            $timestamp = date('Y-m-d H:i:s', $bonus);

            $data = [
                'UserID' => $check[0]['Id'],
                'Information1'  => $this->request->getVar('ip'),
                'Information2'  => $this->request->getVar('hdid'),  
                'PackageIndex'  => $this->request->getVar('updaten'),         
                'PlanIndex' => 1,       
                'ProductId' => $this->request->getVar('plan'),
                'Status' => $this->request->getVar('status'),
                'Expire' =>  $timestamp  
            ];
            $licenseModel->insert($data);
            return redirect()->to('/admin/addlicense')->with('msg', 'Licensa adicionada ao usuário ['.$check[0]['Name'].'].'); 
        
        }
        }else{
            return redirect()->to('/admin/addlicense')->with('error', $this->validator); 
        
        }
          
    }
  
}
