<?

include 'system/sys.php';
include 'system/funcs.php';

if (!isset ($us)) {
        header ('location: /');
        exit;
}

$items = DB :: $dbs -> querySingle ("SELECT COUNT(*) FROM `favorit` WHERE (`kem`='" . $us['id'] . "')");
H ('Избранные', 'Избранные вами (' . $items . ' чел.)');

if (isset ($_GET['u'])) {
        $query = DB :: $dbs -> query ("SELECT * FROM `us` WHERE (`id`=?)", array (intval ($_GET['u'])));
        if ($query -> rowCount () == 0) {
                header ('location: /favorit.php');
                exit;
        }
        $u = $query -> fetch ();
        if ($u['id']==$us['id']) {
                header ('location: /favorit.php');
                exit;
        }
        
        if (DB :: $dbs -> querySingle ("SELECT COUNT(*) FROM `favorit` WHERE (`kem`='" . $us['id'] . "') AND (`us`='" . $u['id'] . "')") != 0) {
                header ('location: /favorit.php');
                exit;
        }
        DB :: $dbs -> query ("INSERT INTO `favorit` (`us`, `kem`) VALUES ('" . $u['id'] . "', '" . $us['id'] . "')");
        echo '<div class="lst"><b>' . uNick ($u['id']) . '</b> добавлен в избранное!</div>';
        
        
        header ('refresh: 1; url=/favorit.php');
        
}

$items_per_page = 10;
$pages = ceil ( $items / $items_per_page );
$page = (int) $_GET['page'];

if ($page < 1) {
        $page = 1;
}
if ($page > $pages) {
        $page = $pages;
}

$start = $page * $items_per_page - $items_per_page;


if ($items == 0) {
        echo '<div class="list1">Избранных нет..</div>';
}
else {

        if (isset ($_GET['del'])) {
                $_GET['del'] = intval ($_GET['del']);
                
                if (DB :: $dbs -> querySingle ("SELECT COUNT(*) FROM `favorit` WHERE (`kem`='" . $us['id'] . "') AND (`us`=?)", array ($_GET['del'])) != 0) {
                        DB :: $dbs -> query ("DELETE FROM `favorit` WHERE (`kem`='" . $us['id'] . "') AND (`us`=?)", array ($_GET['del']));
                }

                header ('location: /favorit.php');
        }

        $query = DB :: $dbs -> query ("SELECT * FROM `favorit` WHERE (`kem`='" . $us['id'] . "') LIMIT $start, $items_per_page");
        while ($favorit = $query -> fetch ()) {
                echo '<div class="lst">' . uNick ($favorit['us']) . ' [<a href="/favorit.php?del=' . $favorit['us'] . '">x</a>]</div>';
        }
        
        echo '<div class="list1"><a href="/kab">Личный кабинет</a></div>';
        echo '<div class="lst">' . pages ('/favorit') . '</div>';
        
}

F ();

?>