<?php

function login_kuri(){


    if (isset($_POST['username']) and isset($_POST['password'])){
        $result = api_login($_POST['username'], $_POST['password']);

        if (isset($result['error'])){
            $error = $result['error'];
        }


        if (isset($result['data'])) {
            
            add_user_cookie($result['data']['client_id'], $result['data']['clientpassword']);
            header('Location: '.SITE.'mybooks');
        }    
                 
    }
    
   // if (isset($_COOKIE['chitatel'])){
   //     out();
  //  }

    $tempcontent =  VIEWPATH.'login.phtml';
    include VIEWPATH.'layout_lite.phtml'; 

    return true;

}


function out_kuri(){

    if (isset($_COOKIE['chitatel'])) {
        unset($_COOKIE['chitatel']); 
        setcookie('chitatel', null, -1,'/', $_SERVER['HTTP_HOST']); 
    }   
    
    if (isset($_COOKIE['code'])) {
         unset($_COOKIE['code']); 
        setcookie('code', null, -1, '/', $_SERVER['HTTP_HOST']);   
    }    

    header('Location: '.SITE.'login');


}


function add_user_cookie($user, $pwd){

    $timeout = time()+(60*60*24*30);

  //  ini_set ("session.use_trans_sid", true);
   // session_start();

   $secret = client_secret($user, $pwd);

    setcookie ("chitatel", $user, $timeout, '/', $_SERVER['HTTP_HOST']);
    setcookie ("code", $secret, $timeout, '/', $_SERVER['HTTP_HOST']);   

}



function check_login_kuri(){
 //ini_set ("session.use_trans_sid", true);
    //session_start(); 
    
    $client = client_check_auth($_COOKIE['chitatel'], $_COOKIE['code']);
    
    if (!isset($client['data'])){
      return  $client;
    }
    else {
        return $client['data'];
    }


     
    //$_SESSION['id'] = $row['id'];   //записываем в сессию id пользователя     


}


function redirect_login(){
    header('Location: '.SITE.'login');
    exit;
}






// if(password_verify($_POST["password"],$hashed_password))

function resetpwd_kuri($hash){

    $url = "/resetpwd/$hash";
    $minlen = 5;
    $viewform = true;

    $client = client_find_hash($hash);

    if (isset($client['error'])) {
        $error = $client['error'];
        $viewform = False;
        
    }  
    else if ($client['clientpassword'] !== ''){
        $error = 'Пароль уже был изменен';
        $viewform = False;
    }

    if (isset($_POST['reset-submit'])){ //пришла форма 
       
        $result = client_add_password($client['client_id'], $_POST['new-password'], $_POST['confirm-password'], $minlen);
        if (isset($result['newpassword'])){
            add_user_cookie($client['client_id'], $result['newpassword']);
            $linklab  = SITE.'mybooks';
            $viewform = False;
        }  
        else {
            $error = $result['error'];
        }  

    }
       
   

    $tempcontent =  VIEWPATH.'reset.phtml';
    include VIEWPATH.'layout_lite.phtml'; //центральный шаблон

    
   


}