<?php
session_start();
include('db.php');

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

$user_id = $_SESSION['user_id'];

// 리뷰 삭제 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_review_id'])) {
    $delete_review_id = (int)$_POST['delete_review_id'];
    $stmt = $conn->prepare("DELETE FROM reviews WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ii", $delete_review_id, $user_id);
    $stmt->execute();

    if ($stmt->affected_rows > 0) {
        $_SESSION['success_message'] = "리뷰가 삭제되었습니다.";
    } else {
        $_SESSION['error_message'] = "리뷰 삭제에 실패했습니다.";
    }
    $stmt->close();

    header('Location: mypage.php');
    exit();
}

// 책갈피 삭제 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_bookmark_id'])) {
    $delete_bookmark_id = (int)$_POST['delete_bookmark_id'];
    $stmt = $conn->prepare("DELETE FROM bookmarks WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ii", $delete_bookmark_id, $user_id);
    $stmt->execute();

    if ($stmt->affected_rows > 0) {
        $_SESSION['success_message'] = "책갈피가 삭제되었습니다.";
    } else {
        $_SESSION['error_message'] = "책갈피 삭제에 실패했습니다.";
    }
    $stmt->close();

    header('Location: mypage.php');
    exit();
}

// 읽은 책 저장 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_read_books'])) {
    $selected_books = isset($_POST['selected_books']) ? $_POST['selected_books'] : [];
    $conn->begin_transaction();

    try {
        $stmt = $conn->prepare("DELETE FROM user_read_books WHERE user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $stmt->close();

        if (count($selected_books) > 0) {
            $stmt = $conn->prepare("INSERT INTO user_read_books (user_id, book_id, read_date) VALUES (?, ?, NOW())");
            foreach ($selected_books as $book_id) {
                $book_id = intval($book_id);
                $stmt->bind_param("ii", $user_id, $book_id);
                $stmt->execute();
            }
            $stmt->close();
        }
        $conn->commit();
        $_SESSION['success_message'] = "읽은 책 목록이 업데이트되었습니다.";
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = "읽은 책 목록 저장 중 오류가 발생했습니다.";
    }

    header('Location: mypage.php');
    exit();
}

// 리뷰 제출 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_review'])) {
    $book_id = (int)$_POST['book'];
    $rating = (int)$_POST['rating'];
    $content = $_POST['content'];

    $stmt = $conn->prepare("INSERT INTO reviews (user_id, book_id, rating, content) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("iiis", $user_id, $book_id, $rating, $content);
    $stmt->execute();
    $stmt->close();

    $_SESSION['success_message'] = "리뷰가 성공적으로 작성되었습니다.";
    header('Location: mypage.php');
    exit();
}

// 책갈피 추가 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_bookmark'])) {
    $book_id = (int)$_POST['bookmark_book'];
    $page = (int)$_POST['bookmark_page'];
    $memo = trim($_POST['bookmark_memo']);

    $stmt = $conn->prepare("INSERT INTO bookmarks (user_id, book_id, page, memo) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("iiis", $user_id, $book_id, $page, $memo);
    if ($stmt->execute()) {
        $_SESSION['success_message'] = "책갈피가 추가되었습니다.";
    } else {
        $_SESSION['error_message'] = "책갈피 추가에 실패했습니다.";
    }
    $stmt->close();

    header('Location: mypage.php');
    exit();
}

// 기존 읽은 책 데이터 조회
$user_read_books_ids = [];
$stmt = $conn->prepare("SELECT book_id FROM user_read_books WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    $user_read_books_ids[] = $row['book_id'];
}
$stmt->close();

// 카테고리별 책 목록 조회
$categories = [];
$stmt = $conn->prepare("SELECT c.id AS category_id, c.name AS category_name, b.id AS book_id, b.title FROM categories c LEFT JOIN books b ON c.id = b.category_id ORDER BY c.name, b.title");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $categories[$row['category_name']][] = $row;
}
$stmt->close();

// 책갈피 조회
$bookmarks = [];
$stmt = $conn->prepare("SELECT bm.*, b.title FROM bookmarks bm JOIN books b ON bm.book_id = b.id WHERE bm.user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$bookmarks = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// 리뷰 조회
$reviews = [];
$stmt = $conn->prepare("SELECT r.*, b.title FROM reviews r JOIN books b ON r.book_id = b.id WHERE r.user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$reviews = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>My Page</title>
<link rel="stylesheet" href="css/styles.css" />
<style>

    body {
        margin: 0 auto;
        font-family: Arial, sans-serif;
        background-color: #f3f4f6;
        width: 1280px;
    }
/* 메시지 */
.success-message, .error-message {
    border-radius: 8px;
    padding: 12px 18px;
    margin-bottom: 20px;
    font-weight: 600;
    font-size: 1rem;
    box-sizing: border-box;
    animation: fadein 0.7s ease forwards;
}

.success-message {
    background-color: #dff0d8;
    color:rgb(160, 233, 161);
    border: 1.5px solid rgb(201, 245, 202);
}

.error-message {
    background-color: #f8d7da;
    color: #842029;
    border: 1.5px solid #842029;
}

@keyframes fadein {
    from {opacity: 0;}
    to {opacity: 1;}
}

/* 읽은 책 영역 */
/* 읽은 책 체크박스 폼에만 적용되도록 클래스 추가 */
.read-books-form {
    background: white;
    padding: 20px 25px;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(80, 71, 222, 0.15);
    margin-bottom: 40px;
}


form h2 {
    font-weight: 700;
    font-size: 1.6rem;
    color: #5047de;
    margin-bottom: 12px;
}

/* 카테고리별 책 리스트 */
.category-section {
    margin-bottom: 22px;
}

.category-title {
    font-weight: 700;
    font-size: 1.25rem;
    color: #6a54c1;
    border-bottom: 2.5px solid #a49efb;
    padding-bottom: 4px;
    margin-bottom: 12px;
    user-select: none;
}

.category-book {
    display: block;
    margin-left: 18px;
    font-size: 1rem;
    font-weight: 500;
    color: #222222;
    cursor: pointer;
    user-select: none;
    padding: 3px 0;
}

.category-book input[type="checkbox"] {
    margin-right: 10px;
    transform: scale(1.15);
    cursor: pointer;
}

button[type="submit"][name="save_read_books"] {
    background: linear-gradient(to right,rgb(149, 136, 250),rgb(184, 174, 255));
    color: white;
    border: none;
    border-radius: 10px;
    padding: 10px 26px;
    font-weight: 600;
    font-size: 1.1rem;
    cursor: pointer;
    box-shadow: 0 3px 10px rgba(110, 91, 230, 0.45);
    transition: background-color 0.3s ease;
    user-select: none;
}

button[type="submit"][name="save_read_books"]:hover {
    background-color: #8473f2;
}

/* 책갈피 및 리뷰 기존 스타일 유지 */
.mypage-item-box .book-title {
    color: #000000 !important;
}
.category-section {
    margin-bottom: 30px;
}
.category-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 10px;
    color: #6a54c1;
}
.bookmark-item {
    margin-bottom: 20px;
    background: linear-gradient(to bottom right, #f5f7fa, #e4e7ee);
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
    transition: transform 0.2s ease, box-shadow 0.3s ease;
}

.bookmark-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.12);
}

.bookmark-item .book-title {
    font-weight: bold;
    font-size: 17px;
    color: #333;
    margin-bottom: 6px;
}

.bookmark-form {
    background: linear-gradient(to bottom right, #ffffff, #f9f9ff);
    padding: 30px;
    border-radius: 16px;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
    margin: 0 auto;
    font-family: 'Segoe UI', sans-serif;
}

.bookmark-form label {
    display: block;
    margin-top: 15px;
    margin-bottom: 8px;
    font-weight: bold;
    color: #333;
    font-size: 15px;
}

.bookmark-form input[type="text"],
.bookmark-form textarea {
    width: 100%;
    padding: 12px;
    font-size: 15px;
    border-radius: 10px;
    border: 1px solid #ccc;
    transition: border 0.3s ease, box-shadow 0.3s ease;
}

.bookmark-form input[type="text"]:focus,
.bookmark-form textarea:focus {
    border-color: #a499f2;
    box-shadow: 0 0 5px rgba(164, 153, 242, 0.4);
    outline: none;
}

.bookmark-form button {
    background: linear-gradient(to right,rgb(149, 136, 250),rgb(184, 174, 255));
    color: white;
    padding: 12px 24px;
    font-size: 16px;
    font-weight: bold;
    border-radius: 12px;
    cursor: pointer;
    border: none;
    margin-top: 20px;
    transition: background 0.3s ease, transform 0.2s ease;
}

.bookmark-form button:hover {
    background: linear-gradient(to right, #b2a6ff, #dedbff); /* 백그라운드 색상 그라데이션*/
    transform: scale(1.02);
}

.bookmark-form button:active {
    transform: scale(0.98);
}

/* 리뷰 작성 폼 스타일 - 개선 버전 */
.review-form {
    background: linear-gradient(to bottom right, #ffffff, #f9f9ff);
    padding: 30px;
    border-radius: 16px;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
    margin: 0 auto;
    font-family: 'Segoe UI', sans-serif;
}

.review-form label {
    display: block;
    margin: 15px 0 8px;
    font-weight: 600;
    color: #444;
}

.review-form textarea {
    width: 100%;
    padding: 12px 15px;
    font-size: 15px;
    border-radius: 12px;
    border: 1px solid #ccc;
    background-color: #fff;
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
    resize: vertical;
    transition: border 0.3s ease;
}

.review-form textarea:focus {
    outline: none;
    border-color: #a499f2;
    box-shadow: 0 0 0 3px rgba(164, 153, 242, 0.2);
}

.review-form input[type="number"] {
    width: 80px;
    padding: 8px;
    font-size: 15px;
    border-radius: 10px;
    border: 1px solid #ccc;
    background-color: #fff;
    transition: border 0.3s ease;
}

.review-form input[type="number"]:focus {
    outline: none;
    border-color: #a499f2;
    box-shadow: 0 0 0 3px rgba(164, 153, 242, 0.2);
}

.review-form button {
    background: linear-gradient(to right,rgb(149, 136, 250),rgb(184, 174, 255));
    color: white;
    padding: 12px 28px;
    font-size: 16px;
    border-radius: 12px;
    cursor: pointer;
    border: none;
    transition: background-color 0.3s ease, transform 0.2s ease;
    margin-top: 20px;
    display: inline-block;
}

.review-form button:hover {
    background-color: #8c7ae6;
    transform: translateY(-2px);
}

.review-form button:active {
    transform: scale(0.98);
}

.review-item {
    margin-bottom: 20px;
    background: linear-gradient(to bottom right, #f5f7fa, #e4e7ee);
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
    transition: transform 0.2s ease, box-shadow 0.3s ease;
}

.review-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.12);
}

.review .book-title {
    font-weight: bold;
    font-size: 17px;
    color: #333;
    margin-bottom: 6px;
}

.mypage-item-box {
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 10px;
    box-shadow: 0 2px 6px rgba(180, 180, 255, 0.2);
    transition: background-color 0.3s, border-color 0.3s;
}

.bookmark-item form {
    display: inline-block;
    margin-left: 10px;
}

</style>
</head>
<body>

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>보관함 - ReadUS</title>
    <link rel="stylesheet" href="css/styles.css">
</head>

<body>
    <!-- 헤더 섹션: 상단 로고 및 메뉴 -->
    <div class="header page-section">
        <div class="logo">
            <a href="index.php">ReadUS</a> <!-- 클릭 시 홈으로 이동 -->
        </div>
        <div class="menu">
            <?php if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true): ?>
                <!-- 로그인 되어있으면 사용자 이름과 주요 메뉴 링크 보여주기 -->
                <span class="welcome-message"><?php echo htmlspecialchars($_SESSION['username']); ?>님</span>
                <a href="edit-profile.php" title="회원정보 수정">⚙️</a>
                <a href="logout.php" title="로그아웃">🚪</a>
                <a href="mypage.php" title="MyPage">📚</a>
                <a href="wishlist.php" title="보관함">💖</a>
                <a href="cart.php" title="장바구니">🛒</a>
            <?php else: ?>
                <!-- 로그인 안 되어있으면 로그인, 회원가입 링크만 보여주기 -->
                <a href="login.php" title="로그인">🔐</a>
                <a href="signup.php" title="회원가입">👤</a>
            <?php endif; ?>
        </div>
    </div>

<!-- 성공 / 실패 메시지 영역 -->
<?php if (isset($_SESSION['success_message'])): ?>
    <div id="successMsg" class="success-message"><?=htmlspecialchars($_SESSION['success_message'])?></div>
    <?php unset($_SESSION['success_message']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['error_message'])): ?>
    <div id="errorMsg" class="error-message"><?=htmlspecialchars($_SESSION['error_message'])?></div>
    <?php unset($_SESSION['error_message']); ?>
<?php endif; ?>

<!-- 읽은 책 체크박스 폼 -->
<!-- 읽은 책 체크박스 폼 -->
<form method="POST" class="read-books-form">
    <h2> 📖읽은 책 선택</h2>
    <?php foreach ($categories as $catName => $books): ?>
        <div class="category-section">
            <div class="category-title"><?= htmlspecialchars($catName) ?></div>
            <?php foreach ($books as $book): ?>
                <?php if (!$book['book_id']) continue; ?>
                <label class="category-book">
                    <input type="checkbox" name="selected_books[]" value="<?= $book['book_id'] ?>"
                        <?= in_array($book['book_id'], $user_read_books_ids) ? 'checked' : '' ?> >
                    <?= htmlspecialchars($book['title']) ?>
                </label>
            <?php endforeach; ?>
        </div>
    <?php endforeach; ?>
    <button type="submit" name="save_read_books">저장</button>
</form>


<!-- 책갈피 섹션 -->
<div class=".mypage-item-box">
    <h2> 🔖책갈피 및 메모 </h2>
    <div class="bookmark-form">
        <form method="POST">
            <label for="bookmark_book">책 선택</label>
            <select name="bookmark_book" required>
                <?php foreach ($categories as $category_name => $books): ?>
                    <?php foreach ($books as $book): ?>
                        <option value="<?= $book['book_id'] ?>"><?= htmlspecialchars($book['title']) ?></option>
                    <?php endforeach; ?>
                <?php endforeach; ?>
            </select>

            <label for="bookmark_page">페이지</label>
            <input type="number" name="bookmark_page" min="1" required>

            <label for="bookmark_memo">메모</label>
            <textarea name="bookmark_memo" rows="3" required></textarea>

            <button type="submit" name="add_bookmark">책갈피 추가</button>
        </form>
    </div>

    <?php if (count($bookmarks) > 0): ?>
        <?php foreach ($bookmarks as $bm): ?>
            <div class="bookmark-item">
                <strong class="book-title"><?= htmlspecialchars($bm['title']) ?> - <?= htmlspecialchars($bm['page']) ?>페이지</strong><br />
                메모: <?= nl2br(htmlspecialchars($bm['memo'])) ?>
            <form method="POST" style="display: inline-block; margin-left: 10px;">
                <input type="hidden" name="delete_bookmark_id" value="<?= $bm['id'] ?>">
                <button type="submit" class="mypage-delete-btn">삭제</button>
            </form>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <p>책갈피가 없습니다.</p>
    <?php endif; ?>


<!-- 리뷰 작성 폼 -->
<div class="review-form">
    <h2> 📝리뷰 작성</h2>
    <form method="POST" action="mypage.php">
        <label for="book">책 선택:</label>
        <select name="book" id="book" required>
            <option value="" disabled selected>책을 선택하세요</option>
            <?php foreach ($categories as $books): ?>
                <?php foreach ($books as $book): ?>
                    <?php if ($book['book_id']): ?>
                        <option value="<?=htmlspecialchars($book['book_id'])?>"><?=htmlspecialchars($book['title'])?></option>
                    <?php endif; ?>
                <?php endforeach; ?>
            <?php endforeach; ?>
        </select>

        <label for="rating">평점 (1-5):</label>
        <input type="number" name="rating" id="rating" min="1" max="5" required>

        <label for="content">리뷰 내용:</label>
        <textarea name="content" id="content" rows="4" required></textarea>

        <button type="submit" name="submit_review">리뷰 제출</button>
    </form>
</div>

<!-- 리뷰 목록 -->
<div class="review-list">
    <h2> 📋내 리뷰 목록</h2>
    <?php if (count($reviews) > 0): ?>
        <?php foreach ($reviews as $review): ?>
            <div class="review-item">
                <strong><?= htmlspecialchars($review['title']) ?></strong> (평점: <?= htmlspecialchars($review['rating']) ?>)<br>
                <?= nl2br(htmlspecialchars($review['content'])) ?><br>
                <form method="POST" style="margin-top: 5px; display: inline;">
                    <input type="hidden" name="delete_review_id" value="<?= htmlspecialchars($review['id']) ?>">
                    <button type="submit" class="mypage-delete-btn">삭제</button>
                </form>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <p>작성한 리뷰가 없습니다.</p>
    <?php endif; ?>
</div>


<script>
  // 메시지 3초 후 자동 사라지기
  window.addEventListener('DOMContentLoaded', () => {
    const successMsg = document.getElementById('successMsg');
    const errorMsg = document.getElementById('errorMsg');
    if (successMsg) {
      setTimeout(() => {
        successMsg.style.transition = 'opacity 0.6s';
        successMsg.style.opacity = '0';
        setTimeout(() => successMsg.remove(), 600);
      }, 3000);
    }
    if (errorMsg) {
      setTimeout(() => {
        errorMsg.style.transition = 'opacity 0.6s';
        errorMsg.style.opacity = '0';
        setTimeout(() => errorMsg.remove(), 600);
      }, 3000);
    }
  });
</script>

</body>
</html>
<div class="footer-box page-section">
        <div class="footer-item">안산대학교</div>
        <div class="footer-item">010-0000-0000</div>
        <div class="footer-item">shinyourim@ansan.ac.kr</div>
    </div>

</body>
</html>
