<?php
$id = intval($_GET['id']);
$userid = intval($_GET['user']);
$data = DB:: $pdo->queryFetch("SELECT * FROM `{$table}` WHERE `id` = ? AND `id_user` = ? LIMIT 1;", array($id, $userid));

$ank = profile:: getUser($data['id_user']);

if (!isset($data['id'])) {
    system:: redirect("Фотографии не существует.", "{$thisLink}{$userid}", 1);
}



$actionPhoto = '';
$accessEdit = (isset($user['id']) ? admin:: getAccess($user, array('a' => 3, 'm_chat' => 1)) : '');
$thisNumber = (isset($_GET['p']) ? abs(intval($_GET['p'])) : 0);
$ids = (filter_has_var(INPUT_GET, 'ids') === true ? (int)$_GET['ids'] : -1);
if (isset($user['id'])) {
    if (filter_has_var(INPUT_GET, 'c') === true &&
        in_array($_GET['c'], ['edit', 'delete', 'response']) === true &&
        filter_has_var(INPUT_GET, 'access') === true && $_GET['access'] == ACCESS) {
        $c = system:: check($_GET['c']);
        $photosComments = DB:: $pdo->queryFetch("SELECT * FROM `photos_comments` WHERE `id` = ? LIMIT 1;", [$ids]);
        if ($photosComments === false) {
            system:: redirect("Сообщение не найдено.", "{$thisLink}{$ank['id']}/view{$data['id']}" . (!empty($thisNumber) ? '?p=' . $thisNumber : ''));
        } else {
            switch ($c) {
                case 'edit':
                    if ($photosComments['id_user'] == $user['id'] || $accessEdit) {
                        $actionPhoto = $c;
                    } else
                        system:: redirect("Ошибка доступа.", "{$thisLink}{$ank['id']}/view{$data['id']}");
                    break;
                case 'delete':
                    if ($ank['id'] == $user['id'] || $photosComments['id_user'] == $user['id'] || $accessEdit) {
                        DB:: $pdo->query("DELETE FROM `photos_comments` WHERE `id` = ?;", [$ids]);
                        system:: redirect("Сообщение успешно удалено.", "{$thisLink}{$ank['id']}/view{$data['id']}");
                    } else
                        system:: redirect("Ошибка доступа.", "{$thisLink}{$ank['id']}/view{$data['id']}");
                    break;
                case 'response':
                    if($photosComments['id_user'] != $user['id']) {
                        $actionPhoto = $c;
                    } else
                        system:: redirect("Ошибка доступа.", "{$thisLink}{$ank['id']}/view{$data['id']}");
                    break;
            }
        }
    }
    if (filter_has_var(INPUT_POST, 'cfms') === true) {
        $mess = system:: check($_POST['message']);
        $msg_str = system:: utf_strlen($mess);
        if ($msg_str >= 1) {
            if ($msg_str <= 100000) {
                $m_db = DB:: $pdo->querySingle("SELECT COUNT(*) FROM `photos_comments` WHERE `id_user` = ? AND `id_photo` = ? AND `time` > ? AND `message` = ?;", array($user['id'], $data['id'], (time() - 600), $mess));
                if ($m_db == 0) {
                    $time_m = time();
                    switch($actionPhoto) {
                        case 'edit':
                            DB:: $pdo->query("UPDATE `photos_comments` SET `message` = ? WHERE `id` = ?;", array($mess, $photosComments['id']));
                            system:: redirect("Сообщение изменено.", "{$thisLink}{$ank['id']}/view{$data['id']}" . (!empty($thisNumber) ? '?p=' . $thisNumber : ''));
                            break;
                        case 'response':
                            DB:: $pdo->query("INSERT INTO `photos_comments` (`id_user`, `id_photo`, `id_otvet`, `time`, `message`) VALUES (?, ?, ?, ?, ?);", array($user['id'], $data['id'], $photosComments['id_user'], $time_m, $mess));
                            notif::init()->comment_photo(['id_user' => $photosComments['id_user'], 'id_last' => $user['id'], 'id_obj' => $data['id'], 'notices_text' =>$mess]);
                            DB:: $pdo->query("UPDATE `users` SET `count_new_notice` = `count_new_notice`+1 WHERE `id` = ? LIMIT 1;", [$photosComments['id_user']]);
                            system:: redirect("Успешно ответили на комментарий.", "{$thisLink}{$ank['id']}/view{$data['id']}" . (!empty($thisNumber) ? '?p=' . $thisNumber : ''));
                            break;
                        default:
                            DB:: $pdo->query("INSERT INTO `photos_comments` (`id_user`, `id_photo`, `time`, `message`) VALUES (?, ?, ?, ?);", array($user['id'], $data['id'], $time_m, $mess));
                            if($ank['id'] != $user['id']) {
                                notif::init()->add_comment_photo(['id_user' => $ank['id'], 'id_last' => $user['id'], 'id_obj' => $data['id'], 'notices_text' =>$mess]);
                                DB:: $pdo->query("UPDATE `users` SET `count_new_notice` = `count_new_notice`+1 WHERE `id` = ? LIMIT 1;", [$ank['id']]);
                            }
                            system:: redirect("Сообщение отправлено.", "{$thisLink}{$ank['id']}/view{$data['id']}");
                            break;
                    }
                } else {
                    $errMsg = "Сообщение повторяет предыдущее.";
                }
            } else {
                $errMsg = "Сообщение превышает 1000 знаков.";
            }
        } else {
            $errMsg = "Пустое сообщение.";
        }
    }
}

if (isset($_GET['edit']) && isset($user['id']) && $user['id'] == $ank['id']) {
    require("edit.php");
}
if (isset($_GET['set']) && @$user['id'] == $ank['id'] && @$_GET['access'] == ACCESS) {
    if ($_GET['set'] == "avatar") {
        $qarr = ($id == $user['avatar'] ? array(NULL, 0, "", $user['id']) : array($data['hash'], $id, $data['key'], $user['id']));
        DB:: $pdo->query("UPDATE `users` SET `info_avatar` = ?, `avatar` = ?, `count_avatar` = ? WHERE `id` = ?;", $qarr);

//			DB :: $pdo -> query("UPDATE `{$table}` SET `avatar` = ? WHERE `id` = ? LIMIT 1;",[ ($id == $user['avatar'] ? 0 : 1 ), $data['id'] ]);

        system:: redirect("Фотография успешно " . ($id == $user['avatar'] ? 'убрана.' : 'поставлена.'), profile:: getLink($user));
    } else if ($_GET['set'] == "delete") {

        unlink(FILES_PATH . system:: photosGetView($data['hash'],1));
        unlink(FILES_PATH . system:: photosGetView($data['hash'],2));
        unlink(FILES_PATH . system:: photosGetView($data['hash'],3));
        unlink(FILES_PATH . system:: photosGetView($data['hash'],4));
        unlink(FILES_PATH . system:: photosGetView($data['hash'],5));
        unlink(FILES_PATH . system:: photosGetView($data['hash'],6));
        unlink(FILES_PATH . system:: photosGetView($data['hash'],0));

        if ($user['avatar'] == $data['id']) {
            $qarr[] = NULL;
            $qarr[] = 0;
        }

        $qarr[] = $user['id'];
        DB:: $pdo->query("UPDATE `users` SET `count_photos` = `count_photos`-1" . ($user['avatar'] == $data['id'] ? ", `info_avatar` = ?, `avatar` = ?" : '') . " WHERE `id` = ? LIMIT 1;", $qarr);
        DB:: $pdo->query("UPDATE `{$table_a}` SET `count` = `count`-1 WHERE `id` = ? LIMIT 1;", array($data['id_album']));
        DB:: $pdo->query("DELETE FROM `{$table}` WHERE `id` = ? LIMIT 1;", array($data['id']));
        DB:: $pdo->query("DELETE FROM `photos_comments` WHERE `id_photo` = ?;", [$data['id']]);

        system:: redirect("Фотография успешно удалена.", "{$thisLink}{$data['id_user']}/album{$data['id_album']}");
    }
}

$title = "Фотографии - Просмотр фотографии";
$l = "Фотографии - Просмотр фотографии";
$lBack ="{$thisLink}{$data['id_user']}/album{$data['id_album']}";
require(CORE . "head.php");
if (isset($errMsg)) {
    echo system:: show($errMsg);
}
echo "<div class=\"app-block\">";
//$back = system:: back("{$thisLink}{$data['id_user']}/album{$data['id_album']}", "".language::text('back', $language, 'photo')."", true);

echo $back;
$browser = new browser();
?>
    <div class="list">


        <div class=" _center">
            <img src="<?= FILES_SERVER . system:: photosGetView($data['hash'], (!$browser->isMobile() ? "5" : "4")) ?>">
        </div>
        <div class="_gray _font-s">
            <?= system:: check($data['desc']) ?>
        </div>
    </div>
    <div class="list _bg-gray">
<?if ($user['id'] == $data['id_user']) {?>
 <div>
                            <a class="toggle-menu-act" onclick="UI.toggleMenu(this);">
                                <span></span>
                            </a>
                            <div class="toggle-menu">
                            <div class="toggle-menu-arrow"><span></span></div>
                            <ul class="toggle-menu-block">
                                <a href="<?=$thisLink?><?=$user['id']?>/view<?=$data['id']?>/?edit=1"><?=language::text('edit', $language, 'photo');?></a>
                                <a href="<?=$thisLink?><?=$user['id']?>/view<?=$data['id']?>/?set=delete&amp;access=<?=$user['access']?>"><?=language::text('dell', $language, 'photo');?></a>
                                
                            </ul>
                            </div>
</div>
<?}?>
        <span class="_gray"><?=language::text('time', $language, 'photo');?>:</span> <?= system:: times($data['time']) ?><br/>
        <span class="_gray"><?=language::text('user', $language, 'photo');?>:</span> <span class="_name"><?= profile:: goPage($ank, true) ?></span>
    </div>
<?php
echo system:: touch(FILES_SERVER . system:: photosGetView($data['hash'], 0) . "\" prevent=\"1\" target=\"_blank\"", system:: icon('dl') . " ".language::text('download', $language, 'photo')." <span class=\"_gray\">({$data['width']}x{$data['height']}, " . system:: FBytes($data['size']) . ")</span>");
if ($user['id'] == $data['id_user']) {
    echo
        

        system:: touch("{$thisLink}{$user['id']}/view{$data['id']}/?set=avatar&amp;access={$user['access']}", system:: icon('photos') . ($data['id'] == $user['avatar'] ? " ".language::text('delava', $language, 'photo')."" : "".language::text('addava', $language, 'photo')."") . "");
        }

?>


    
        <div class="">
            <?php if (isset($user['id'])) { ?>
                <form method="post" class="post-add" action="">
                    <textarea name="message" id="emoji-textarea" data-id="emoji-block_1" class="app-textarea"
                              placeholder="Введите комментарий.."><?= ($actionPhoto == 'edit' ? emoji:: decode($photosComments['message']) : '') ?></textarea>
                    <div class="list _bg-gray">
                        <div class="_p-rel">
                            <input type="submit" class="main-btn" name="cfms"
                                   value="<?= ($actionPhoto == 'edit' ? "Сохранить" : ($actionPhoto == 'response' ? 'Ответить' : 'Отправить')) ?>">
                            <?= emoji:: Smiles("emoji-block_1", "emoji-textarea") ?>
                            <?php
                                if($actionPhoto == 'response') {
                                    ?>
                                    <span class="_gray">Ответ пользователю:</span>
                                    <span class="_name"><?= profile:: goPage(profile:: getUser($photosComments['id_user'], "id, info_first_name, info_last_name, last_time", false), false) ?></span>
                                    <?
                                }
                            ?>
                        </div>
                    </div>
                </form>
            <?php } else { ?>
                <div class="list _center _gray _font-s">
                    Для того, чтобы писать комментарии к фото сначала <a href="/" class="_bold">войдите</a> или <a
                            href="/signup" class="_bold">зарегистрируйтесь</a>.
                </div>
            <?php } ?>
        </div>
    
<?php


$query = "SELECT * FROM `photos_comments` WHERE `id_photo` = '" . $data['id'] . "' ORDER by `time` DESC ";
$total = DB:: $pdo->querySingle("SELECT COUNT(*) FROM `photos_comments` WHERE `id_photo` = '" . $data['id'] . "'");

if ($total > 10) {
    $p = (($_GET['p']) ? intval($_GET['p']) : 1);
    $pagination = new pagination(10, $total, $p);
    $query .= $pagination->limit;
}

$q = DB:: $pdo->query("{$query}");

$i = 0;
$in = 0;

echo '<div class="post-list-all">';
while ($r = $q->fetch()) {
    $dataUser = ($r['id_user'] == $user['id'] ? $user : profile:: getUser($r['id_user'], "*", false));
    if ($actionPhoto == 'edit' && $r['id'] == $ids && ($r['id_user'] == $user['id'] || $accessEdit)) {
        $class = " edit_msg";
    } else $class = "";
    ?>
    <div class="list<?= $class; ?>">
        <?php
        if (isset($user['id'])) {
            $url = $thisLink . $ank['id'] . '/view' . $data['id'] . '/' . (!empty($pagination) ? '?p=' . $pagination->page . '&amp;' : '?');
            if ($r['id_user'] == $user['id'] || $accessEdit) {
                $actionsLink[] = ['link' => $url . "c=edit&amp;ids={$r['id']}&amp;access=" . ACCESS, 'text' => "Редактировать"];
            }
            if($ank['id'] == $user['id'] || $r['id_user'] == $user['id'] || $accessEdit) {
                $actionsLink[] = ['link' => $url . "c=delete&amp;ids={$r['id']}&amp;access=" . ACCESS, 'text' => "Удалить"];
            }
            if ($r['id_user'] != $user['id']) {
                $actionsLink[] = ['link' => $url . "c=response&amp;ids={$r['id']}&amp;access=" . ACCESS, 'text' => "Ответить"];
            }
            echo UI:: toggleMenu($actionsLink);
            unset($actionsLink);
        }
        ?>


        <div class="_oh">

            <div class="list-flex">
                <div class="post-l emotion-show" data-emotions="<?=system::textOut($dataUser['emotions'])?>">
                    <?= profile:: userAvatar($dataUser, 3) ?>
                </div>
                <div class="post-c">
                    <div style="display: block;"><span class="_name"><?= profile:: goPage($dataUser) ?></span>
                        <div><span class="_font-m _gray"><?= system:: times($r['time']) ?></span></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="_oh"><span style="vertical-align: sub;">
            <?php
            if($r['id_otvet'] > 0) {
                ?><span class="_name"><?= profile:: goPage(profile:: getUser($r['id_otvet'], "id, info_first_name, info_last_name, last_time", false), false) ?>, </span><?
            }
            ?>
            <?= emoji:: Text(system:: BBcode(system:: textOut($r['message']))) ?></span>
        </div>
    </div>
    <?php
}
echo "</div>";
if ($total > 10) echo $pagination->printPages($thisLink . $ank['id'] . '/view' . $data['id'] . '/?');

require(CORE . "foot.php");