View file zip0.ru/profile_edit.php

File size: 10.41Kb
<?php
require_once 'db.php';

if (empty($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_id = (int)$_SESSION['user_id'];

if (is_banned($user_id)) {
    include 'header.php';
    echo '<p>Ваш аккаунт заблокирован. Обратитесь в поддержку.</p>';
    include 'footer.php';
    exit;
}

$errors = [];
$success = false;

// текущие данные
$stmt = $mysqli->prepare("
    SELECT email, name, gender, birthday, city, about, photo
    FROM users
    WHERE id = ?
");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($email, $name, $gender, $birthday, $city, $about, $photo);
$stmt->fetch();
$stmt->close();

// текущие интересы
$current_interests = [];
$stmt = $mysqli->prepare("SELECT interest FROM interests WHERE user_id = ?");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    $current_interests[] = $row['interest'];
}
$stmt->close();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name     = trim($_POST['name'] ?? '');
    $gender   = $_POST['gender'] ?? 'other';
    $birthday = $_POST['birthday'] ?: null;
    $city     = trim($_POST['city'] ?? '');
    $about    = trim($_POST['about'] ?? '');
    $interests = $_POST['interests'] ?? [];

    if ($name === '') {
        $errors[] = 'Имя обязательно';
    }

    // аватар
    if (!empty($_FILES['photo']['name']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
        $ext = strtolower($ext);
        if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
            $errors[] = 'Недопустимый формат аватара';
        } else {
            $filename = 'user_' . $user_id . '_' . time() . '.' . $ext;
            $target = __DIR__ . '/assets/img/' . $filename;
            if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
                $photo = $filename;
            } else {
                $errors[] = 'Не удалось загрузить аватар';
            }
        }
    }

    // если нет критичных ошибок – сохраняем
    if (!$errors) {
        $stmt = $mysqli->prepare("
            UPDATE users
            SET name = ?, gender = ?, birthday = ?, city = ?, about = ?, photo = ?
            WHERE id = ?
        ");
        $stmt->bind_param('ssssssi', $name, $gender, $birthday, $city, $about, $photo, $user_id);
        $stmt->execute();
        $stmt->close();

        // интересы
        $stmt = $mysqli->prepare("DELETE FROM interests WHERE user_id = ?");
        $stmt->bind_param('i', $user_id);
        $stmt->execute();
        $stmt->close();

        foreach ($interests as $interest) {
            $interest = trim($interest);
            if ($interest === '') continue;
            $stmt = $mysqli->prepare("INSERT INTO interests (user_id, interest) VALUES (?, ?)");
            $stmt->bind_param('is', $user_id, $interest);
            $stmt->execute();
            $stmt->close();
        }

        // альбом – множественная загрузка
        if (!empty($_FILES['album_photos']['name'][0])) {
            $count = count($_FILES['album_photos']['name']);
            for ($i = 0; $i < $count; $i++) {
                if ($_FILES['album_photos']['error'][$i] !== UPLOAD_ERR_OK) {
                    continue;
                }
                $ext = strtolower(pathinfo($_FILES['album_photos']['name'][$i], PATHINFO_EXTENSION));
                if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
                    continue;
                }
                $fname = 'album_' . $user_id . '_' . time() . '_' . mt_rand(1000,9999) . '.' . $ext;
                $target = __DIR__ . '/assets/img/' . $fname;
                if (move_uploaded_file($_FILES['album_photos']['tmp_name'][$i], $target)) {
                    $stmt = $mysqli->prepare("INSERT INTO user_photos (user_id, filename) VALUES (?, ?)");
                    $stmt->bind_param('is', $user_id, $fname);
                    $stmt->execute();
                    $stmt->close();
                }
            }
        }

        $success = true;
    }
}

include 'header.php';
?>

<style>
/* Локальные стили только для profile_edit.php */

.profile-edit-page {
    margin-top: 18px;
}

.profile-edit-layout {
    display: grid;
    grid-template-columns: 260px minmax(0, 1fr);
    gap: 20px;
}

.profile-edit-sidebar {
    background: rgba(255,255,255,0.98);
    border-radius: 24px;
    padding: 18px 18px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.06);
    text-align: center;
}

.profile-edit-avatar {
    width: 120px;
    height: 120px;
    border-radius: 999px;
    object-fit: cover;
    margin-bottom: 8px;
}

.profile-edit-main {
    background: rgba(255,255,255,0.98);
    border-radius: 24px;
    padding: 18px 20px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.06);
}

.profile-edit-main h2 {
    margin-top: 0;
    margin-bottom: 10px;
}

.form-row {
    margin-bottom: 10px;
}

.form-row label {
    display: block;
    font-size: 13px;
    margin-bottom: 4px;
}

.form-row input[type="text"],
.form-row input[type="date"],
.form-row select,
.form-row textarea {
    width: 100%;
    box-sizing: border-box;
}

.interests-checkboxes label {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    margin-right: 10px;
    font-size: 13px;
}

@media (max-width: 768px) {
    .profile-edit-layout {
        grid-template-columns: 1fr;
    }
    .profile-edit-sidebar,
    .profile-edit-main {
        margin: 0 -4px;
        border-radius: 18px;
    }
}
</style>

<div class="profile-edit-page">
    <h1>Редактирование профиля</h1>

    <?php if ($success): ?>
        <div class="alert alert-success">Профиль обновлён ✅</div>
    <?php endif; ?>

    <?php if ($errors): ?>
        <div class="alert alert-error">
            <?php foreach ($errors as $e): ?>
                <p><?= htmlspecialchars($e) ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <div class="profile-edit-layout">
        <aside class="profile-edit-sidebar">
            <?php if ($photo): ?>
                <img src="/assets/img/<?= htmlspecialchars($photo) ?>" class="profile-edit-avatar" alt="">
            <?php else: ?>
                <div class="profile-avatar-placeholder" style="width:120px;height:120px;margin:0 auto 8px;">🙂</div>
            <?php endif; ?>
            <div style="font-weight:600;"><?= htmlspecialchars($name ?: 'Без имени') ?></div>
            <?php if ($city): ?>
                <div style="font-size:13px;color:#7b7287;"><?= htmlspecialchars($city) ?></div>
            <?php endif; ?>
            <div style="margin-top:10px;">
                <a href="profile.php" class="btn-outline btn-small">← Вернуться к профилю</a>
            </div>
        </aside>

        <section class="profile-edit-main">
            <h2>Основные данные</h2>

            <form method="post" enctype="multipart/form-data">
                <div class="form-row">
                    <label>Имя</label>
                    <input type="text" name="name" required value="<?= htmlspecialchars($name) ?>">
                </div>

                <div class="form-row">
                    <label>Пол</label>
                    <select name="gender">
                        <option value="m" <?= $gender === 'm' ? 'selected' : '' ?>>Мужчина</option>
                        <option value="f" <?= $gender === 'f' ? 'selected' : '' ?>>Женщина</option>
                        <option value="other" <?= $gender === 'other' ? 'selected' : '' ?>>Другое</option>
                    </select>
                </div>

                <div class="form-row">
                    <label>Дата рождения</label>
                    <input type="date" name="birthday" value="<?= htmlspecialchars($birthday ?? '') ?>">
                </div>

                <div class="form-row">
                    <label>Город</label>
                    <input type="text" name="city" value="<?= htmlspecialchars($city ?? '') ?>">
                </div>

                <div class="form-row">
                    <label>О себе</label>
                    <textarea name="about" rows="4"><?= htmlspecialchars($about ?? '') ?></textarea>
                </div>

                <div class="form-row">
                    <label>Аватар</label>
                    <input type="file" name="photo" accept="image/*">
                    <div style="font-size:12px;color:#7b7287;margin-top:2px;">Рекомендуем квадратное фото, до 3–4 МБ.</div>
                </div>

                <hr style="margin:14px 0;">

                <h2>Интересы</h2>
                <div class="form-row interests-checkboxes">
                    <?php
                    $allInterests = ['Путешествия','Спорт','Музыка','Книги','Технологии','Животные','Кино','Еда','Танцы','Игры'];
                    foreach ($allInterests as $int):
                        $checked = in_array($int, $current_interests, true) ? 'checked' : '';
                    ?>
                        <label>
                            <input type="checkbox" name="interests[]" value="<?= htmlspecialchars($int) ?>" <?= $checked ?>>
                            <?= htmlspecialchars($int) ?>
                        </label>
                    <?php endforeach; ?>
                </div>

                <hr style="margin:14px 0;" id="album">

                <h2>Фотоальбом</h2>
                <div class="form-row">
                    <label>Добавить фото (можно несколько)</label>
                    <input type="file" name="album_photos[]" multiple accept="image/*">
                    <div style="font-size:12px;color:#7b7287;margin-top:2px;">Вы можете загрузить сразу несколько фотографий.</div>
                </div>

                <div style="margin-top:16px;display:flex;gap:10px;flex-wrap:wrap;">
                    <button type="submit" class="btn-primary">Сохранить</button>
                    <a href="profile.php" class="btn-outline">Отменить</a>
                </div>
            </form>
        </section>
    </div>
</div>

<?php include 'footer.php'; ?>