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

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'remove_friend') {
        $friendId = (int)$_POST['friend_id'];
        $conn->query("DELETE FROM friends WHERE user_id = $userId AND friend_id = $friendId");
        $conn->query("DELETE FROM friends WHERE user_id = $friendId AND friend_id = $userId");
        $conn->query("DELETE FROM friend_requests WHERE 
            (sender_id = $userId AND receiver_id = $friendId) OR
            (sender_id = $friendId AND receiver_id = $userId)");
        $_SESSION['message'] = "친구가 삭제되었습니다.";
        header('Location: friends.php');
        exit;
    }

    if ($_POST['action'] === 'send_friend_request') {
        header('Content-Type: application/json; charset=utf-8');

        if (!isset($_POST['friend_id'])) {
            echo json_encode(['error' => '친구 ID가 전달되지 않았습니다.']);
            exit;
        }

        $friendId = (int)$_POST['friend_id'];

        if ($friendId === $userId) {
            echo json_encode(['error' => '본인에게 친구 요청을 보낼 수 없습니다.']);
            exit;
        }

        $checkFriendSql = "SELECT 1 FROM friends WHERE user_id = $userId AND friend_id = $friendId";
        $checkFriendResult = $conn->query($checkFriendSql);
        if ($checkFriendResult && $checkFriendResult->num_rows > 0) {
            echo json_encode(['error' => '이미 친구입니다.']);
            exit;
        }

        $checkSentRequestSql = "SELECT 1 FROM friend_requests WHERE sender_id = $userId AND receiver_id = $friendId AND status = 'pending'";
        $checkSentRequestResult = $conn->query($checkSentRequestSql);
        if ($checkSentRequestResult && $checkSentRequestResult->num_rows > 0) {
            echo json_encode(['error' => '이미 친구 요청을 보냈습니다.']);
            exit;
        }

        $checkReceivedRequestSql = "SELECT 1 FROM friend_requests WHERE sender_id = $friendId AND receiver_id = $userId AND status = 'pending'";
        $checkReceivedRequestResult = $conn->query($checkReceivedRequestSql);
        if ($checkReceivedRequestResult && $checkReceivedRequestResult->num_rows > 0) {
            echo json_encode(['error' => '상대방이 이미 친구 요청을 보냈습니다. 받은 요청 목록에서 확인해 주세요.']);
            exit;
        }

        $now = date('Y-m-d H:i:s');
        $insertRequestSql = "INSERT INTO friend_requests (sender_id, receiver_id, status, created_at) VALUES ($userId, $friendId, 'pending', '$now')";
        if ($conn->query($insertRequestSql)) {
            echo json_encode(['successMessage' => '요청 중']);
        } else {
            echo json_encode(['error' => '친구 요청 전송 중 오류가 발생했습니다.']);
        }
        exit;
    }
}

// 검색, 받은 요청, 친구 목록 가져오기
$searchResults = [];
$receivedRequests = [];
$friendsList = [];

if (isset($_GET['search']) && !empty(trim($_GET['search']))) {
    $search = $conn->real_escape_string(trim($_GET['search']));
    $sql = "
        SELECT u.id, u.username,
            (SELECT status FROM friend_requests WHERE sender_id = $userId AND receiver_id = u.id LIMIT 1) AS request_status,
            (SELECT COUNT(*) FROM friends WHERE user_id = $userId AND friend_id = u.id) AS is_friend
        FROM users u
        WHERE u.username LIKE '%$search%' AND u.id != $userId
        LIMIT 10
    ";
    $result = $conn->query($sql);
    while ($row = $result->fetch_assoc()) {
        $searchResults[] = $row;
    }
}

$sql = "
    SELECT fr.id, u.username, u.id as sender_id
    FROM friend_requests fr
    JOIN users u ON fr.sender_id = u.id
    WHERE fr.receiver_id = $userId AND fr.status = 'pending'
";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
    $receivedRequests[] = $row;
}

$sql = "
    SELECT u.id, u.username
    FROM friends f
    JOIN users u ON f.friend_id = u.id
    WHERE f.user_id = $userId
    ORDER BY u.username ASC
";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
    $friendsList[] = $row;
}
?>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>친구 추가</title>
    <link rel="stylesheet" href="css/styles.css">
</head>
<style>
    body {
        margin: 0 auto;
        font-family: Arial, sans-serif;
        background-color: #f3f4f6;
        width: 1280px;
    }
</style>
<body>
<?php if (isset($_SESSION['message'])): ?>
    <div class="alert success"><?php echo htmlspecialchars($_SESSION['message']); unset($_SESSION['message']); ?></div>
<?php elseif (isset($_SESSION['error'])): ?>
    <div class="alert error"><?php echo htmlspecialchars($_SESSION['error']); unset($_SESSION['error']); ?></div>
<?php endif; ?>

<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($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>

<div class="friend-wrapper page-section">
    <h2 class="section-title">👥 친구 추가</h2>
    <form method="GET" action="friends.php" class="friend-search-form">
        <input type="text" name="search" placeholder="닉네임 검색" value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>" required>
        <button type="submit">검색</button>
    </form>

    <?php if (!empty($searchResults)): ?>
        <ul class="friend-search-results">
            <?php foreach ($searchResults as $user): ?>
                <li id="user-<?php echo $user['id']; ?>">
                    <?php echo htmlspecialchars($user['username']); ?>
                    <?php if ((int)$user['is_friend'] === 1): ?>
                        <span>✅ 친구</span>
                    <?php elseif ($user['request_status'] === 'pending'): ?>
                        <span class="status-text">요청 중</span>
                    <?php else: ?>
                        <button class="send-friend-request-btn" data-user-id="<?php echo $user['id']; ?>">친구 요청</button>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>

    <hr>

    <h3>받은 친구 요청</h3>
    <?php if (empty($receivedRequests)): ?>
        <p>받은 친구 요청이 없습니다.</p>
    <?php else: ?>
        <ul class="received-friend-requests">
            <?php foreach ($receivedRequests as $req): ?>
                <li id="friend-request-<?php echo $req['id']; ?>" data-friend-id="<?php echo $req['sender_id']; ?>" data-friend-name="<?php echo htmlspecialchars($req['username']); ?>">
                    <?php echo htmlspecialchars($req['username']); ?> 님의 요청
                    <button class="accept-btn" data-request-id="<?php echo $req['id']; ?>">✅ 수락</button>
                    <button class="reject-btn" data-request-id="<?php echo $req['id']; ?>">❌ 거절</button>
                    <span class="request-status-message"></span>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>

    <hr>

    <h3>내 친구 목록</h3>
    <ul class="friends-list" id="friends-list">
        <?php if (empty($friendsList)): ?>
            <li class="no-friends">친구가 없습니다.</li>
        <?php else: ?>
            <?php foreach ($friendsList as $friend): ?>
                <li id="friend-<?php echo $friend['id']; ?>">
                    <?php echo htmlspecialchars($friend['username']); ?>
                    <form method="POST" style="display:inline-block;" onsubmit="return confirm('친구를 삭제하시겠습니까?');">
                        <input type="hidden" name="friend_id" value="<?php echo $friend['id']; ?>">
                        <input type="hidden" name="action" value="remove_friend">
                        <button type="submit">친구 삭제</button>
                    </form>
                </li>
            <?php endforeach; ?>
        <?php endif; ?>
    </ul>
</div>
<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>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
    $('.send-friend-request-btn').click(function() {
        var userId = $(this).data('user-id');
        var $li = $('#user-' + userId);
        var $button = $(this);

        $.ajax({
            url: 'friends.php',
            type: 'POST',
            data: { action: 'send_friend_request', friend_id: userId },
            dataType: 'json',
            success: function(response) {
                if(response.error) {
                    alert(response.error);
                } else if(response.successMessage) {
                    $button.remove();
                    $li.append('<span class="status-text">' + response.successMessage + '</span>');
                }
            },
            error: function() {
                alert('서버 오류가 발생했습니다.');
            }
        });
    });

    $('.accept-btn').click(function() {
        var requestId = $(this).data('request-id');
        var $li = $('#friend-request-' + requestId);
        var friendId = $li.data('friend-id');
        var friendName = $li.data('friend-name');
        var $statusMsg = $li.find('.request-status-message');

        $.ajax({
            url: 'respond_friend_request.php',
            method: 'POST',
            data: {
                request_id: requestId,
                action: 'accept'
            },
            dataType: 'json',
            success: function(response) {
                if(response.success) {
                    $statusMsg.text(response.message).css('color', 'green');
                    $li.find('button').prop('disabled', true);

                    setTimeout(function() {
                        $statusMsg.fadeOut('fast', function() {
                            $li.remove();

                            $('#friends-list .no-friends').remove();
                            $('#friends-list').append(`
                                <li id="friend-${friendId}">
                                    ${friendName}
                                    <form method="POST" style="display:inline-block;" onsubmit="return confirm('친구를 삭제하시겠습니까?');">
                                        <input type="hidden" name="friend_id" value="${friendId}">
                                        <input type="hidden" name="action" value="remove_friend">
                                        <button type="submit">친구 삭제</button>
                                    </form>
                                </li>
                            `);
                        });
                    }, 1000);
                } else {
                    $statusMsg.text(response.message).css('color', 'red');
                }
            },
            error: function() {
                $statusMsg.text('서버 오류가 발생했습니다.').css('color', 'red');
            }
        });
    });

    $('.reject-btn').click(function() {
        var requestId = $(this).data('request-id');
        var $li = $('#friend-request-' + requestId);
        var $statusMsg = $li.find('.request-status-message');

        $.ajax({
            url: 'respond_friend_request.php',
            method: 'POST',
            data: {
                request_id: requestId,
                action: 'reject'
            },
            dataType: 'json',
            success: function(response) {
                if(response.success) {
                    $statusMsg.text(response.message).css('color', 'gray');
                    $li.find('button').prop('disabled', true);
                    setTimeout(function() {
                        $statusMsg.fadeOut('slow', function() {
                            $li.remove();
                        });
                    }, 3000);
                } else {
                    $statusMsg.text(response.message).css('color', 'red');
                }
            },
            error: function() {
                $statusMsg.text('서버 오류가 발생했습니다.').css('color', 'red');
            }
        });
    });

    setTimeout(function() {
        $('.alert').fadeOut('slow');
    }, 3000);
});
</script>
</body>
</html>
