<?php 

include_once $_SERVER['DOCUMENT_ROOT'].'/sys/inc/home.php';
include_once H.'sys/inc/start.php';
include_once H.'sys/inc/compress.php';
include_once H.'sys/inc/sess.php';
include_once H.'sys/inc/settings.php';
include_once H.'sys/inc/db_connect.php';
include_once H.'sys/inc/ipua.php';
include_once H.'sys/inc/fnc.php';
include_once H.'sys/inc/user.php';

require(dirname(__FILE__) . '/config.php');

$set['title'] = $title;
include_once H.'sys/inc/thead.php';
title();
aut();
err();

$search = '';
if (isset($_GET['q'])) {
    $search = preg_replace('/[^a-zа-я0-9\s]/ui', '', $_GET['q']);;
    
    if ($search) {
        $search_exp = explode(" ", $search);    
    }
    $build = array();
    
    if (isset($search_exp)) {
        foreach($search_exp AS $key => $value) {
            if ($value) {
                if (is_numeric($value)) {
                    $build['HAVING']['age'] = $value;
                } elseif (isset($build['HAVING']['age']) || $key == 2) {
                    $build['WHERE']['city'] = $value;
                    break;
                } elseif ($key <= 1) {
                    $build['WHERE']['name'][] = $value;
                }
            }
        }
    }
}

$age_from = (isset($_GET['age_from']) && $_GET['age_from'] ? abs((int) $_GET['age_from']) : '');
$age_to = (isset($_GET['age_to']) && $_GET['age_to'] ? abs((int) $_GET['age_to']) : '');
$orien = (int) $tools->keyGlobals('orien', 'get', 100);
$target = (int) $tools->keyGlobals('target', 'get', 0);
$age = '';
$sex = '';
$online = '';
$order = (isset($user) ? 'priority' : 'rating');
$sorting = '';

if (isset($_GET['order']) && preg_match('/^(new|priority|rating)$/i', $_GET['order'])) {
    $order = (!isset($user) && $_GET['order'] == 'priority' ? 'rating' : $_GET['order']);
}

if (isset($_GET['sex']) && ($_GET['sex'] == 0 || $_GET['sex'] == 1)) {
    $sex = $_GET['sex'];
}

if ($age_from && $age_from == $age_to) {
    $age = $age_from;
} elseif (isset($build['HAVING']['age'])) {
    $age = $build['HAVING']['age'];
}

$where = array();

if ($_ONLY_DATING) {
    $only_dating = array();
    foreach($_ARR_TARGET AS $key => $value) {
        $only_dating[] = "u.ank_lov_$key = '1'";
    }
    $where[] = '(' . implode(' OR ', $only_dating) . ')';
}
 
if (isset($_GET['online']) && $_GET['online']) {
    $online = 1;
    $where[] = "u.date_last > '" . ($time - $_ONLINE_TIME) . "'";
}

if (isset($build['WHERE']['city'])) {
    $_GET['city'] = $build['WHERE']['city'];
}

$city = $tools->keyGlobals('city', 'get', '');

if ($city) 
$city = mysql_fetch_assoc(mysql_query("SELECT * FROM city 
                                       WHERE city_id = " . (int) $city . " OR name = '" . my_esc($city) . "'"));



if (!$city && $city !== '') {
    if (isset($user)) {
        $city_search = $user['ank_city'];
        $city = mysql_fetch_assoc(mysql_query("SELECT * FROM city WHERE name = '$city_search'"));
    }
    
    if (!$city) {
        $city = mysql_fetch_assoc(mysql_query("SELECT * FROM city WHERE name = '$_CITY_DEFAULT'"));
    }
}

if (!$city)
    $city_str = $city;
else 
    $city_str = text($city['name']);


if ($city) {
    $where[] = "u.ank_city = '" . $city['name'] . "'";
} else {
    $city['name'] = 'Не указан';
}

$rating = array();

if (isset($user)) {
    if ($orien == 100 || $orien == 0) {
        $where[] = "u.ank_orien = '$user[ank_orien]'";
    }
    
    if ($order == 'priority') {
        foreach($_ARR_TARGET AS $key => $value) {
            if ($user['ank_lov_'.$key] == 1) {
                $sorting .= "FIND_IN_SET(u.ank_lov_$key, '" . $user['ank_lov_'.$key] . "') DESC,";
                $rating[$key] = 1;
            }
        }
        
        if ($sex === '' && $user['ank_orien'] == 1) {
            $sorting .= "FIND_IN_SET(u.pol, '" . ($user['pol'] == 1 ? 0 : 1) . "') DESC,";
        } 
    }
}

if ($orien && $orien > 0 && $orien <= 3 && $orien != 100) {
    $where[] = "u.ank_orien = '$orien'";
}

if ($sex == '0' || $sex == '1') {
    $where[] = "u.pol = '$sex'";
}

if ($target && $target > 0 && $target <= count($_ARR_TARGET)) {
    $where[] = "u.ank_lov_$target = '1'";
}

if (isset($user)) {
    $where[] = "u.id != '" . $user['id'] . "'";
}

if (isset($build['WHERE']['name'])) {
    if (count($build['WHERE']['name']) == 2) {
        $case = SexCase($build['WHERE']['name'][0], $build['WHERE']['name'][1]);
        
        $where[] = "((u.ank_name like '%" . my_esc($case['first_name']) . "%' OR u.ank_family like '%" . my_esc($case['last_name']) . "%') OR (u.ank_name like '%" . my_esc($case['last_name']) . "%' OR u.ank_family like '%" . my_esc($case['first_name']) . "%'))";
        
        $sorting .= "FIND_IN_SET(u.ank_family, '" . my_esc($case['last_name'])."') DESC, 
                     FIND_IN_SET(u.ank_name, '" . my_esc($case['first_name'])."') DESC, 
                     FIND_IN_SET(u.pol, '$case[gender]') DESC,";
    } else {
        $case = SexCaseOne($build['WHERE']['name'][0]);
        
        $where[] = "(u.$case[type] like '%" . my_esc($build['WHERE']['name'][0]) . "%')";

        $sorting .= "FIND_IN_SET(u.$case[type], '" . my_esc($build['WHERE']['name'][0])."') DESC, 
                     FIND_IN_SET(u.pol, '$case[gender]') DESC,";
    }
}

$having = array();

if ($age) {
    $having[] = 'age = ' . $age;
} else {
    if ($age_from) {
      $having[] = 'age > ' . ($age_from - 1);
    }

    if ($age_to) {
      $having[] = 'age < ' . ($age_to + 1);
    }  
}

if ($order == 'new') {
    $sorting .= "u.id";
} else {
    $sorting .= 'u.rating';
}

$has_photo = 0;
if (isset($_GET['has_photo']) && $_GET['has_photo'] == 1) {
  $has_photo = 1;
}

$options = 0;
if (isset($_GET['options']) && $_GET['options'] == 1) {
  $options = 1;
}

$join = array();
if ($has_photo == 1) {
  $join[] = "JOIN gallery_foto AS f ON u.id = f.id_user AND f.avatar = '1'";
}

$query = "SELECT (YEAR( 
          CURRENT_TIMESTAMP ) - u.ank_g_r + IF( MONTH( 
          CURRENT_TIMESTAMP ) < u.ank_m_r, -1, IF( MONTH( 
          CURRENT_TIMESTAMP ) = u.ank_m_r
          AND DAY( 
          CURRENT_TIMESTAMP ) < u.ank_d_r, -1, 0 ) ) 
          ) AS 'age' 
          FROM user AS u " . 
          ($join ? implode(' ', $join) : '') . 
          ($where ? "WHERE " . implode(' AND ', $where) : '') .
          ($having ? " HAVING " . implode(' AND ', $having) : '');

$q = mysql_query($query);
$count = mysql_num_rows($q);
$k_page = k_page($count, $_PAGE_COUNT);
$page = page($k_page);  
$offset = ceil($_PAGE_COUNT * $page - $_PAGE_COUNT);

$query = "SELECT u.*, (YEAR( 
          CURRENT_TIMESTAMP ) - u.ank_g_r + IF( MONTH( 
          CURRENT_TIMESTAMP ) < u.ank_m_r, -1, IF( MONTH( 
          CURRENT_TIMESTAMP ) = u.ank_m_r
          AND DAY( 
          CURRENT_TIMESTAMP ) < u.ank_d_r, -1, 0 ) ) 
          ) AS 'age' 
          FROM user AS u " .
          ($join ? implode(' ', $join) : '') . 
          ($where ? "WHERE " . implode(' AND ', $where) : '') .
          ($having ? " HAVING " . implode(' AND ', $having) : '') . 
          " ORDER BY $sorting DESC LIMIT $offset, " . $_PAGE_COUNT;
          
$_MTP = array(
    'form' => array(
        'q' => text($search),
        'age' => $age,
        'age_to' => $age_to,
        'age_from' => $age_from,
        'sex' => $sex,
        'order' => $order,
        'online' => $online,
        'page' => $page,
        'has_photo' => $has_photo,
        'options' => $options,
        'city' => $city_str,
        'orien' => $orien,
        'target' => $target,
    ),
);

$_MTP['item'] = array();

$q = mysql_query($query);

$i = 0;
while($ank = mysql_fetch_assoc($q)) {
    
    $compatibility = 0;
    $compatibility_all = (count($rating) + 1);
    
    foreach($rating AS $key => $value) {
        if ($ank['ank_lov_'.$key] == $user['ank_lov_'.$key]) {
            $compatibility++;
        }
    }

    if (isset($user) && $user['ank_orien'] == $ank['ank_orien']) {
        $compatibility++;
    }
    
    $_MTP['item'][$i] = array(
        'id' => $ank['id'],
        'nickname' => user::nick($ank['id'], 1, 1, 1),
        'first_name' => text($ank['ank_name']),
        'last_name' => text($ank['ank_family']),
        'age' => $ank['age'],
        'city' => text($ank['ank_city']),
        'avatar' => user::avatar($ank['id'], $_AVATAR_CONF),
        'online' => ($ank['date_last'] > ($time - $_ONLINE_TIME) ? 'online' : 'offline'),
        'rating' => $ank['rating'],
        'orien' => ($ank['ank_orien'] != 3 ? $_ARR_ORIEN[$ank['ank_orien']] : $_ARR_ORIEN[3][$ank['pol']]),
    );
    
    if (isset($user) && $order == 'priority') {
        $_MTP['item'][$i]['compatibility'] = ceil($compatibility / $compatibility_all * 100) . '%';
    }
    
    $i++;
}

$_MTP['tpl_file'] = $_PAGE_DEFAULT;
$_MTP['pages'] = $k_page;
$_MTP['http_build'] = http_build_query($_MTP['form']);
$_MTP['count_item'] = $count;

if (is_file(dirname(__FILE__) . '/tpl/' . $_MTP['tpl_file'])) {
    require(dirname(__FILE__) . '/tpl/' . $_MTP['tpl_file']);
}

require_once H.'sys/inc/tfoot.php';