<?php

function api_client_kuri($hash){

    $sql = "SELECT client_id, clientgroup_id FROM `clients` WHERE `clienthash` = '$hash' LIMIT 1 ";
    $client = db_get($sql);

    if (isset($client['client_id']))
        return $client;
    
    return false;

}


function api_login($login, $password){

    $sqlogin = "SELECT `client_id`, `clientpassword` FROM `clients` WHERE `clientmail` = '$login' LIMIT 1";
    $client = dbl_get($sqlogin);

    if (!isset($client['clientpassword']))
        return ['error'=>'пользователь не найден'];

    if ($client['clientpassword'] == '')
        return ['error'=>'необходимо получить ссылку для доступа'];    

    if (!password_verify($password, $client['clientpassword'])) 
        return ['error' => 'неверный пароль'];

    return ['data' => $client];    

}


function clientbuys_kuri($client_id, $page = 1, $category_id = 1, $group_id = null, $filter = null){

    if ($group_id == 1 or $group_id == 2){
        return clients_arch($page, $category_id,  $filter);
    }

    $sql_sub = "SELECT number_id FROM anbuy WHERE client_id = '$client_id'  AND `number_id` = 486  AND `buy_status` = '1' LIMIT 1"; //есть ли активная подписка
    $findsub =  db_get($sql_sub);

    
   if (isset($findsub['number_id'])) {// есть поп
        return clients_arch($page, $category_id, $filter);
    }    

    if ($filter !== 'all'){
        $between = "AND BeginDate BETWEEN '$filter-01-11' AND '$filter-12-31'";
    }
    else
        $between = '';

   $limit  = 28;
   $countsql = "
   SELECT 
        DISTINCT COUNT(buy_id) as count 
    FROM 
        `anbuy` 
    WHERE 
        `client_id` = $client_id 
        AND `buy_status` = '1' 
        $between
    LIMIT 1
   ";
   
   $buycount = db_get($countsql);

    $buysql = "
    SELECT DISTINCT
        price_id, pricehash, pricename, priceimg
    FROM 
        anbuy 
    LEFT JOIN 
        price ON anbuy.number_id = price.price_id
    WHERE 
        client_id = '$client_id' AND `buy_status` = '1' 
        AND category_id = $category_id 
        $between   
    ORDER BY 
        `buy_id` DESC
    LIMIT 
        $limit
    ";

    if ($page > 1){
        $offset = $limit * ($page -1);
        $pricesql .= " OFFSET $offset";
    }    

    $books = db_get($buysql);

    $result['books'] = clientbooks($books, $client_id);
    $result['count'] =  $buycount['count'];

    return $result;

}



function client_find_email_kuri($mail){

    if (!filter_var($mail, FILTER_VALIDATE_EMAIL))
        return ['error' => 'некорректный email'];

    $pwd_query = "SELECT `clienthash` FROM `clients` WHERE `clientmail` = '$mail' LIMIT 1";
    $client = db_get($pwd_query);

    if (isset($client['clienthash']))
        return $client;
    else
        return ['error' => 'client not found'];   

}

function client_find_hash($hash){


    $pwd_query = "SELECT * FROM `clients` WHERE `clienthash` = '$hash' LIMIT 1";
    $client = db_get($pwd_query);

    if (isset($client['client_id']))
        return $client;
    else
        return ['error' => 'client not found'];   

}


function client_find_id($id) {

    $id_query = "SELECT * FROM `clients` WHERE `client_id` = '$id' LIMIT 1";
    $client = db_get($id_query);

    if (!isset($client['client_id'])){
        return ['error' => 'client not found'];    
    }

    return ['result' => $client];

}


function client_check_auth($login, $pwd){
        
    $check_query = "SELECT * FROM `clients` WHERE `client_id` = '$login' LIMIT 1";

    $client = dbl_get($check_query);

    if (!isset($client['client_id'])){
        return ['error' => 'client not found'];
    }

    $hash_pwd = client_secret($client['client_id'], $client['clientpassword']);
    

    if ($pwd == $hash_pwd){
        return ['data' => $client];
    }
    else {
       return ['error' => 'invalid hash'];
    }   
        
}


function client_secret($id, $password){
   $secret = md5($id.$password);
   //echo "$id + $password = $secret<br>";
    return $secret;
}


function client_add_password($client_id, $password, $confirm, $minlen = 5){


    if ($password == ''){
        return 'пароль не задан';
    }    
    
    if (strlen($password) < $minlen) {
        return  "пароль должен быть не менее $maxlen символов";
    }

    if ($password !== $confirm){
        return "пароли не совпадают";
    }

    $clientpassword = password_hash($password, PASSWORD_DEFAULT);  
    $sqlupdate = "UPDATE `clients` SET `clientpassword` = '$clientpassword' WHERE `client_id` = '$client_id'";

   
    $result =  db_get($sqlupdate, 'chitatel');
  


    return ['newpassword' => $clientpassword];

}



function clientmail($mail, $hash){

    $client = db_get("SELECT * FROM `clients` WHERE `clientmail` = $mail LIMIT 1");

    if (!isset($client['client_id'])){
        echo 'Не верный запрос';
        return;
    }


    if ($client['clienthash'] !== $hash){
        echo 'Не верный запрос';
        return;
    }



}



//весь активный архив
function clients_arch($page = 16, $category_id = 1, $filter = 'all'){

    $limit = 28;


    if ($filter !== 'all'){
        $between = "AND BeginDate BETWEEN '$filter-01-11' AND '$filter-12-31'";
    }
    else
        $between = '';

    $countsql = "
    SELECT 
        COUNT(price_id) AS count 
    FROM 
        price
    WHERE 
        category_id = $category_id
        $between
        AND 
            `active` = 1
    LIMIT 1
    ";

    $count = db_get($countsql);

    
    $pricesql = "
    SELECT 
        price_id, pricehash, pricename, priceimg 
    FROM 
        price 
    WHERE 
        category_id = $category_id
        $between 
        AND 
            `active` = 1
    ORDER BY 
        price_id DESC
    LIMIT $limit
    ";


    if ($page > 1){
        $offset = $limit * ($page -1);
        $pricesql .= " OFFSET $offset";
    }    

    $books = db_get($pricesql);

    $result['books'] = clientbooks($books);
    $result['subscript'] = true;
    $result['count'] = $count['count'];

    return $result;

}


function clientbooks($books){


    if (!is_array($books))
        return null;


    foreach($books as $book){
        $book['pic'] = IMGSRV."price/180x280/{$book['price_id']}.{$book['priceimg']}";
        $book['link'] = SITE.'read/'.$book['pricehash'];
        $result[] = $book;
    }

    return $result;

}