<?php

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

        $data['title'] = 'Login';
        $data['msg'] = $this->session->getFlashdata('msg');
        $data['error'] = $this->session->getFlashdata('error');
        $this->smartyView('auth/signin', $data);
    }
    public function checkLicense($id = false)
    {
        $session = session();
        $licenseModel = new LicenseModel();
        $license = $licenseModel->where('UserID', $id)->findAll();
        $time = time();
        if(!empty($license[0])){
            $timestamp = strtotime($license[0]['Expire']);
            if($timestamp < $time){

                $data = [
                    'Status'     => 0,
                ];
                $licenseModel->update($id, $data);
            }     
        } 
    }
  

    public function loginAuth()
    {
        $session = session();
        $userModel = new UserModel();
        $user = $this->request->getVar('user');
        $email = $this->request->getVar('email');
        $password = $this->request->getVar('password');
        
        $data = $userModel->where('Name', $user)->findAll();
        
        if($data){
            $this->checkLicense($data[0]['Id']);
            $pass = $data[0]['Password'];
            $authenticatePassword = $password == $pass ? true : false;
            if($authenticatePassword){
                if($data[0]['Status'] !== 16){
                    $ses_data = [
                        'id' => $data[0]['Id'],
                        'name' => $data[0]['Name'],
                        'email' => $data[0]['Mail'],
                        'isLoggedIn' => TRUE,
                        'Nivel' => $data[0]['Nivel']
                    ];
                    $session->set($ses_data);
                    return redirect()->to('/');
                } else {
                    return redirect()->to('/user/signin')->with('msg', "Conta Banida");  
                }
            }else{
                return redirect()->to('/user/signin')->with('msg', "Senha Incorreta");
            }
        }else{
            return redirect()->to('/user/signin')->with('msg', "Usuario Nao existe");
        }
    }
}
