<?php
session_start(); // 세션 시작
include('db.php'); // DB 연결

// 로그인 상태가 아니면 로그인 페이지로 이동
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: login.php');
    exit;
}

// 로그인된 사용자 정보 저장
$userId = $_SESSION['user_id'];
$username = $_SESSION['username'];
$successMessage = '';
$errorMessage = '';

// 추천 삭제 처리 (본인이 보낸 추천만 삭제 가능)
if (isset($_POST['delete_id'])) {
    $deleteId = $_POST['delete_id'];

    // 추천을 삭제하려는 사용자가 실제로 보낸 추천인지 확인
    $sqlCheck = "SELECT id FROM recommendations WHERE id = ? AND from_user_id = ?";
    $stmtCheck = $conn->prepare($sqlCheck);
    $stmtCheck->bind_param("ii", $deleteId, $userId);
    $stmtCheck->execute();
    $resultCheck = $stmtCheck->get_result();

    if ($resultCheck->num_rows > 0) {
        $stmtCheck->close();

        // 추천 삭제 쿼리 실행
        $sqlDelete = "DELETE FROM recommendations WHERE id = ?";
        $stmtDelete = $conn->prepare($sqlDelete);
        $stmtDelete->bind_param("i", $deleteId);

        if ($stmtDelete->execute()) {
            $successMessage = "추천 내역이 삭제되었습니다.";
        } else {
            $errorMessage = "삭제 중 오류가 발생했습니다.";
        }

        $stmtDelete->close();
    } else {
        $errorMessage = "삭제 권한이 없거나 존재하지 않는 추천 내역입니다.";
    }
}

// 내가 보낸 추천 내역 불러오기
$recommendations_sent = [];
$sqlSent = "
    SELECT r.id, u.username AS friend_name, b.title AS book_title, r.message, r.created_at
    FROM recommendations r
    JOIN users u ON r.receiver_id = u.id
    JOIN books b ON r.book_id = b.id
    WHERE r.from_user_id = ?
    ORDER BY r.created_at DESC
";
$stmtSent = $conn->prepare($sqlSent);
$stmtSent->bind_param("i", $userId);
$stmtSent->execute();
$resultSent = $stmtSent->get_result();
while ($row = $resultSent->fetch_assoc()) {
    $recommendations_sent[] = $row;
}
$stmtSent->close();

// 내가 받은 추천 내역 불러오기
$recommendations_received = [];
$sqlReceived = "
    SELECT r.id, u.username AS sender_name, b.title AS book_title, r.message, r.created_at
    FROM recommendations r
    JOIN users u ON r.from_user_id = u.id
    JOIN books b ON r.book_id = b.id
    WHERE r.receiver_id = ?
    ORDER BY r.created_at DESC
";
$stmtReceived = $conn->prepare($sqlReceived);
$stmtReceived->bind_param("i", $userId);
$stmtReceived->execute();
$resultReceived = $stmtReceived->get_result();
while ($row = $resultReceived->fetch_assoc()) {
    $recommendations_received[] = $row;
}
$stmtReceived->close();
?>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8" />
    <title>추천 내역 관리 - ReadUS</title>
    <link rel="stylesheet" href="css/styles.css" />
    <style>
        /* 페이지 기본 스타일 설정 */
        body {
            margin: 0 auto;
            font-family: Arial, sans-serif;
            background-color: #f3f4f6;
            width: 1280px;
        }

        h2 {
            text-align: center;
            margin-bottom: 30px;
            font-size: 2rem;
            font-weight: 700;
            color: #000;
        }

        /* 상단 메뉴 스타일 */
        .menu {
            display: flex;
            align-items: center;
        }

        .menu a {
            text-decoration: none;
            color: #333;
            font-size: 28px;
            margin-left: 30px;
            transition: transform 0.2s, color 0.3s;
            position: relative;
        }

        .menu a:hover {
            color: #a499f2;
            transform: scale(1.2);
        }

        .menu a::after {
            content: attr(title);
            position: absolute;
            bottom: -35px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #333;
            color: #fff;
            padding: 6px 10px;
            border-radius: 6px;
            white-space: nowrap;
            font-size: 12px;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s, transform 0.3s;
            z-index: 10;
        }

        .menu a:hover::after {
            opacity: 1;
            transform: translateX(-50%) translateY(5px);
        }

        /* 메뉴 반응형 */
        @media screen and (max-width: 768px) {
            .menu a {
                font-size: 22px;
                margin-left: 20px;
            }
        }

        @media screen and (max-width: 480px) {
            .menu {
                justify-content: flex-start;
                flex-wrap: wrap;
                gap: 10px;
            }
        }

        /* 환영 메시지 스타일 */
        .welcome-message {
            padding: 6px 24px 6px 12px;
            background-color: #e6e6fa;
            color: #333;
            font-weight: 600;
            border-radius: 16px;
            font-size: 14px;
            line-height: 1.5;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            margin-left: auto;
            margin-right: auto;
        }

        /* 성공 및 에러 메시지 스타일 */
        .success-message,
        .error-message {
            max-width: 600px;
            margin: 10px auto;
            padding: 12px 20px;
            border-radius: 10px;
            font-weight: 700;
            text-align: center;
        }

        .success-message {
            background-color: #d4edda;
            color: #28a745;
            border: 1px solid #c3e6cb;
        }

        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* 테이블 스타일 */
        table {
            width: 100%;
            max-width: 900px;
            margin: 0 auto 40px;
            border-collapse: collapse;
            background-color: #fff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border-radius: 10px;
            overflow: hidden;
        }

        thead {
            background-color: #a499f2;
            color: #fff;
        }

        th,
        td {
            padding: 14px 20px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        tbody tr:hover {
            background-color: #f0f0ff;
        }

        .no-records {
            text-align: center;
            font-style: italic;
            color: #888;
            margin-top: 50px;
        }

        form.delete-form {
            margin: 0;
        }

        button.delete-btn {
            background-color: #e74c3c;
            border: none;
            padding: 8px 14px;
            color: white;
            font-weight: 600;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button.delete-btn:hover {
            background-color: #c0392b;
        }

        /* 모바일 반응형 테이블 */
        @media (max-width: 600px) {
            table, thead, tbody, th, td, tr {
                display: block;
            }

            thead tr {
                display: none;
            }

            tbody tr {
                margin-bottom: 15px;
                border: 1px solid #ddd;
                border-radius: 10px;
                padding: 12px;
                background: #fff;
            }

            tbody td {
                padding-left: 50%;
                position: relative;
                border: none;
                border-bottom: 1px solid #eee;
            }

            tbody td::before {
                content: attr(data-label);
                position: absolute;
                left: 20px;
                font-weight: 700;
                color: #555;
            }

            button.delete-btn {
                width: 100%;
                padding: 10px 0;
                font-size: 1rem;
            }
        }
    </style>
</head>

<body>
    <!-- 헤더 및 메뉴 -->
    <header class="header">
        <div class="logo">
            <a href="index.php" style="css/styles.css">ReadUS</a>
        </div>
        <nav class="menu">
            <?php if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true): ?>
                <!-- 로그인한 사용자 메뉴 -->
                <span class="welcome-message"><?php echo htmlspecialchars($username); ?>님</span>
                <a href="wishlist.php" title="보관함">💖</a>
                <a href="cart.php" title="장바구니">🛒</a>
                <a href="mypage.php" title="MyPage">📚</a>
                <a href="edit-profile.php" title="회원정보 수정">⚙️</a>
                <a href="logout.php" title="로그아웃">🚪</a>
            <?php else: ?>
                <!-- 비로그인 사용자 메뉴 -->
                <a href="login.php" title="로그인">🔐</a>
                <a href="signup.php" title="회원가입">👤</a>
            <?php endif; ?>
        </nav>
    </header>

    <!-- 내가 보낸 추천 내역 -->
    <h2>내가 보낸 책 추천 내역</h2>
    <?php if (empty($recommendations_sent)): ?>
        <p class="no-records">추천한 내역이 없습니다.</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>추천받은 친구</th>
                    <th>책 제목</th>
                    <th>한마디</th>
                    <th>추천 날짜</th>
                    <th>삭제</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recommendations_sent as $rec): ?>
                    <tr>
                        <td data-label="추천받은 친구"><?php echo htmlspecialchars($rec['friend_name']); ?></td>
                        <td data-label="책 제목"><?php echo htmlspecialchars($rec['book_title']); ?></td>
                        <td data-label="한마디"><?php echo nl2br(htmlspecialchars($rec['message'])); ?></td>
                        <td data-label="추천 날짜"><?php echo htmlspecialchars($rec['created_at']); ?></td>
                        <td data-label="삭제">
                            <!-- 삭제 폼 -->
                            <form class="delete-form" method="POST" onsubmit="return confirm('정말 삭제하시겠습니까?');">
                                <input type="hidden" name="delete_id" value="<?php echo $rec['id']; ?>" />
                                <button type="submit" class="delete-btn">삭제</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>

    <!-- 내가 받은 추천 내역 -->
    <h2>내가 받은 책 추천 내역</h2>
    <?php if (empty($recommendations_received)): ?>
        <p class="no-records">추천 받은 내역이 없습니다.</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>추천해준 친구</th>
                    <th>책 제목</th>
                    <th>한마디</th>
                    <th>추천 날짜</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recommendations_received as $rec): ?>
                    <tr>
                        <td data-label="추천해준 친구"><?php echo htmlspecialchars($rec['sender_name']); ?></td>
                        <td data-label="책 제목"><?php echo htmlspecialchars($rec['book_title']); ?></td>
                        <td data-label="한마디"><?php echo nl2br(htmlspecialchars($rec['message'])); ?></td>
                        <td data-label="추천 날짜"><?php echo htmlspecialchars($rec['created_at']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>

</body>
</html>
