<?php
/**
 * ============================================================================
 * friends/index.php - Enhanced Friends Management Page
 * ============================================================================
 * Facebook-style friends interface with proper image handling
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Friends';
$userId = getUserId();

// Get database connection using Singleton pattern
$database = \App\Database::getInstance();
$db = $database->getConnection();
$friendshipClass = new \App\Friendship($db);

// Get all friends
$friends = $friendshipClass->getFriends($userId);

// Get friend suggestions (people you may know)
$suggestions = $friendshipClass->getFriendSuggestions($userId, 20);

// Get pending friend requests
$pendingRequests = $friendshipClass->getPendingRequests($userId);

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<style>
    .friends-container {
        background: #f0f2f5;
        min-height: 100vh;
    }
    
    .friends-sidebar {
        background: white;
        border-radius: 8px;
        padding: 1rem;
        position: sticky;
        top: 70px;
        height: fit-content;
    }
    
    .sidebar-link {
        display: flex;
        align-items: center;
        padding: 0.75rem;
        color: #050505;
        text-decoration: none;
        border-radius: 8px;
        transition: all 0.2s;
        margin-bottom: 0.25rem;
    }
    
    .sidebar-link:hover {
        background: #f0f2f5;
        color: #050505;
    }
    
    .sidebar-link.active {
        background: #e7f3ff;
        color: #1877f2;
    }
    
    .sidebar-link i {
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #e4e6eb;
        border-radius: 50%;
        margin-right: 12px;
        font-size: 1.1rem;
    }
    
    .sidebar-link.active i {
        background: #1877f2;
        color: white;
    }
    
    .sidebar-link .badge {
        margin-left: auto;
    }
    
    .friends-header {
        background: white;
        padding: 1.5rem;
        border-radius: 8px;
        margin-bottom: 1rem;
    }
    
    .search-box {
        background: #f0f2f5;
        border: none;
        border-radius: 50px;
        padding: 0.75rem 1.5rem;
        width: 100%;
    }
    
    .search-box:focus {
        background: white;
        border: 1px solid #1877f2;
        outline: none;
    }
    
    .friend-card {
        background: white;
        border-radius: 8px;
        overflow: hidden;
        transition: all 0.3s;
        cursor: pointer;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
    }
    
    .friend-card:hover {
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        transform: translateY(-2px);
    }
    
    .friend-card-image {
        width: 100%;
        height: 200px;
        object-fit: cover;
        background: #f0f2f5;
    }
    
    .friend-card-body {
        padding: 1rem;
    }
    
    .friend-name {
        font-weight: 600;
        font-size: 1rem;
        margin-bottom: 0.25rem;
        color: #050505;
    }
    
    .friend-info {
        font-size: 0.875rem;
        color: #65676b;
        margin-bottom: 0.5rem;
    }
    
    .mutual-friends {
        font-size: 0.8125rem;
        color: #65676b;
        margin-bottom: 0.75rem;
    }
    
    .btn-action {
        width: 100%;
        padding: 0.5rem;
        border-radius: 6px;
        font-weight: 600;
        border: none;
        cursor: pointer;
        transition: all 0.2s;
    }
    
    .btn-primary-fb {
        background: #1877f2;
        color: white;
    }
    
    .btn-primary-fb:hover {
        background: #166fe5;
    }
    
    .btn-secondary-fb {
        background: #e4e6eb;
        color: #050505;
    }
    
    .btn-secondary-fb:hover {
        background: #d8dadf;
    }
    
    .btn-danger-fb {
        background: #f02849;
        color: white;
    }
    
    .btn-danger-fb:hover {
        background: #d02345;
    }
    
    .section-title {
        font-size: 1.25rem;
        font-weight: 700;
        color: #050505;
        margin-bottom: 1rem;
    }
    
    .empty-state {
        background: white;
        border-radius: 8px;
        padding: 3rem 2rem;
        text-align: center;
    }
    
    .empty-state i {
        font-size: 4rem;
        color: #d8dadf;
        margin-bottom: 1rem;
    }
    
    .user-type-badge {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 600;
        margin-top: 0.25rem;
    }
    
    .badge-farmer {
        background-color: #d4edda;
        color: #155724;
    }
    
    .badge-buyer {
        background-color: #d1ecf1;
        color: #0c5460;
    }
    
    .badge-extension_officer {
        background-color: #fff3cd;
        color: #856404;
    }
</style>

<div class="friends-container">
    <div class="container py-4">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-lg-3 col-md-4 mb-4">
                <div class="friends-sidebar">
                    <h5 class="mb-3" style="font-weight: 700;">Friends</h5>
                    
                    <a href="#all-friends" class="sidebar-link active" data-section="all-friends">
                        <i class="bi bi-people-fill"></i>
                        <span>All Friends</span>
                        <span class="badge bg-secondary"><?= count($friends) ?></span>
                    </a>
                    
                    <a href="#friend-requests" class="sidebar-link" data-section="friend-requests">
                        <i class="bi bi-person-plus-fill"></i>
                        <span>Friend Requests</span>
                        <?php if (count($pendingRequests) > 0): ?>
                            <span class="badge bg-danger"><?= count($pendingRequests) ?></span>
                        <?php endif; ?>
                    </a>
                    
                    <a href="#suggestions" class="sidebar-link" data-section="suggestions">
                        <i class="bi bi-person-lines-fill"></i>
                        <span>Suggestions</span>
                    </a>
                    
                    <hr>
                    
                    <a href="find-users.php" class="sidebar-link">
                        <i class="bi bi-search"></i>
                        <span>Find People</span>
                    </a>
                    
                    <a href="<?= APP_URL ?>/chat/" class="sidebar-link">
                        <i class="bi bi-messenger"></i>
                        <span>Messages</span>
                    </a>
                </div>
            </div>
            
            <!-- Main Content -->
            <div class="col-lg-9 col-md-8">
                <!-- All Friends Section -->
                <div class="content-section" id="all-friends">
                    <div class="friends-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0" style="font-weight: 700;">Friends (<?= count($friends) ?>)</h4>
                        <input type="text" class="search-box" placeholder="Search friends..." style="max-width: 300px;">
                    </div>
                    
                    <?php if (count($friends) > 0): ?>
                        <div class="row g-3">
                            <?php foreach ($friends as $friend): ?>
                                <div class="col-lg-3 col-md-4 col-sm-6">
                                    <div class="friend-card" onclick="window.location.href='profile.php?id=<?= $friend['friend_user_id'] ?>'">
                                        <img src="<?= APP_URL . '/' . htmlspecialchars($friend['profile_picture']) ?>" 
                                             alt="<?= htmlspecialchars($friend['full_name']) ?>" 
                                             class="friend-card-image"
                                             onerror="this.src='<?= APP_URL ?>/assets/images/default-avatar.png'">
                                        <div class="friend-card-body">
                                            <div class="friend-name"><?= htmlspecialchars($friend['full_name']) ?></div>
                                            <div class="friend-info">
                                                <i class="bi bi-geo-alt"></i> 
                                                <?= htmlspecialchars($friend['district'] ?? 'Unknown') ?>
                                            </div>
                                            <span class="user-type-badge badge-<?= $friend['user_type'] ?>">
                                                <?= ucfirst(str_replace('_', ' ', $friend['user_type'])) ?>
                                            </span>
                                            <div class="mt-3 d-flex gap-2">
                                                <button class="btn-action btn-primary-fb flex-grow-1" 
                                                        onclick="event.stopPropagation(); window.location.href='<?= APP_URL ?>/chat/one-on-one.php?friend_id=<?= $friend['friend_user_id'] ?>'">
                                                    <i class="bi bi-messenger"></i> Message
                                                </button>
                                                <button class="btn-action btn-secondary-fb" 
                                                        onclick="event.stopPropagation(); showUnfriendModal(<?= $friend['friend_user_id'] ?>, '<?= addslashes($friend['full_name']) ?>')">
                                                    <i class="bi bi-three-dots"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="bi bi-people"></i>
                            <h5>No Friends Yet</h5>
                            <p class="text-muted">Connect with farmers, buyers, and extension officers!</p>
                            <a href="find-users.php" class="btn btn-primary btn-lg mt-3">
                                <i class="bi bi-search"></i> Find People
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Friend Requests Section -->
                <div class="content-section" id="friend-requests" style="display: none;">
                    <div class="friends-header">
                        <h4 class="mb-0" style="font-weight: 700;">Friend Requests (<?= count($pendingRequests) ?>)</h4>
                    </div>
                    
                    <?php if (count($pendingRequests) > 0): ?>
                        <div class="row g-3">
                            <?php foreach ($pendingRequests as $request): ?>
                                <div class="col-lg-3 col-md-4 col-sm-6">
                                    <div class="friend-card">
                                        <img src="<?= APP_URL . '/' . htmlspecialchars($request['profile_picture']) ?>" 
                                             alt="<?= htmlspecialchars($request['full_name']) ?>" 
                                             class="friend-card-image"
                                             onerror="this.src='<?= APP_URL ?>/assets/images/default-avatar.png'">
                                        <div class="friend-card-body">
                                            <div class="friend-name"><?= htmlspecialchars($request['full_name']) ?></div>
                                            <div class="friend-info">
                                                <i class="bi bi-geo-alt"></i> 
                                                <?= htmlspecialchars($request['district'] ?? 'Unknown') ?>
                                            </div>
                                            <div class="mutual-friends">
                                                <i class="bi bi-clock"></i> 
                                                <?php
                                                $requestTime = new DateTime($request['requested_at']);
                                                $now = new DateTime();
                                                $diff = $now->diff($requestTime);
                                                if ($diff->days > 0) {
                                                    echo $diff->days . ' day' . ($diff->days > 1 ? 's' : '') . ' ago';
                                                } elseif ($diff->h > 0) {
                                                    echo $diff->h . ' hour' . ($diff->h > 1 ? 's' : '') . ' ago';
                                                } else {
                                                    echo $diff->i . ' minute' . ($diff->i > 1 ? 's' : '') . ' ago';
                                                }
                                                ?>
                                            </div>
                                            <div class="d-flex gap-2">
                                                <button class="btn-action btn-primary-fb flex-grow-1" 
                                                        onclick="respondToRequest(<?= $request['id'] ?>, 'accept', this)">
                                                    <i class="bi bi-check-circle"></i> Confirm
                                                </button>
                                                <button class="btn-action btn-secondary-fb flex-grow-1" 
                                                        onclick="respondToRequest(<?= $request['id'] ?>, 'reject', this)">
                                                    <i class="bi bi-x-circle"></i> Delete
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="bi bi-inbox"></i>
                            <h5>No Pending Requests</h5>
                            <p class="text-muted">You're all caught up!</p>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Suggestions Section -->
                <div class="content-section" id="suggestions" style="display: none;">
                    <div class="friends-header">
                        <h4 class="mb-0" style="font-weight: 700;">People You May Know</h4>
                    </div>
                    
                    <?php if (count($suggestions) > 0): ?>
                        <div class="row g-3">
                            <?php foreach ($suggestions as $suggestion): ?>
                                <div class="col-lg-3 col-md-4 col-sm-6">
                                    <div class="friend-card">
                                        <img src="<?= APP_URL . '/' . htmlspecialchars($suggestion['profile_picture']) ?>" 
                                             alt="<?= htmlspecialchars($suggestion['full_name']) ?>" 
                                             class="friend-card-image"
                                             onerror="this.src='<?= APP_URL ?>/assets/images/default-avatar.png'">
                                        <div class="friend-card-body">
                                            <div class="friend-name"><?= htmlspecialchars($suggestion['full_name']) ?></div>
                                            <div class="friend-info">
                                                <i class="bi bi-geo-alt"></i> 
                                                <?= htmlspecialchars($suggestion['district'] ?? 'Unknown') ?>
                                            </div>
                                            <?php if ($suggestion['mutual_friends_count'] > 0): ?>
                                                <div class="mutual-friends">
                                                    <i class="bi bi-people"></i> 
                                                    <?= $suggestion['mutual_friends_count'] ?> mutual friend<?= $suggestion['mutual_friends_count'] > 1 ? 's' : '' ?>
                                                </div>
                                            <?php endif; ?>
                                            <div class="d-flex gap-2">
                                                <button class="btn-action btn-primary-fb flex-grow-1" 
                                                        onclick="sendFriendRequest(<?= $suggestion['id'] ?>, this)">
                                                    <i class="bi bi-person-plus"></i> Add Friend
                                                </button>
                                                <button class="btn-action btn-secondary-fb" 
                                                        onclick="window.location.href='profile.php?id=<?= $suggestion['id'] ?>'">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="bi bi-lightbulb"></i>
                            <h5>No Suggestions Right Now</h5>
                            <p class="text-muted">Check back later for friend suggestions!</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Unfriend Modal -->
<div class="modal fade" id="unfriendModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-0">
                <h5 class="modal-title">Unfriend <span id="unfriendName"></span>?</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to remove this person from your friends?</p>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmUnfriend">Unfriend</button>
            </div>
        </div>
    </div>
</div>

<!-- Toast Container -->
<div class="position-fixed top-0 end-0 p-3" style="z-index: 11">
    <div id="toast" class="toast align-items-center" role="alert">
        <div class="d-flex">
            <div class="toast-body"></div>
            <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
    // Section navigation
    $('.sidebar-link[data-section]').click(function(e) {
        e.preventDefault();
        const section = $(this).data('section');
        
        // Update active state
        $('.sidebar-link').removeClass('active');
        $(this).addClass('active');
        
        // Show section
        $('.content-section').hide();
        $('#' + section).show();
    });
    
    // Search friends
    $('.search-box').on('input', function() {
        const searchTerm = $(this).val().toLowerCase();
        $('.friend-card').each(function() {
            const name = $(this).find('.friend-name').text().toLowerCase();
            $(this).closest('.col-lg-3').toggle(name.includes(searchTerm));
        });
    });
});

function showToast(message, type = 'success') {
    const toast = document.getElementById('toast');
    const toastBody = toast.querySelector('.toast-body');
    
    toast.classList.remove('bg-success', 'bg-danger', 'text-white');
    toast.classList.add(type === 'success' ? 'bg-success' : 'bg-danger', 'text-white');
    toastBody.textContent = message;
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
}

function sendFriendRequest(friendId, btn) {
    const $btn = $(btn);
    const originalHTML = $btn.html();
    $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
    
    $.post('<?= APP_URL ?>/friends/ajax/send-request.php', {
        friend_id: friendId
    }, function(response) {
        if (response.success) {
            showToast(response.message, 'success');
            $btn.html('<i class="bi bi-check"></i> Request Sent').removeClass('btn-primary-fb').addClass('btn-secondary-fb');
        } else {
            showToast(response.message, 'error');
            $btn.prop('disabled', false).html(originalHTML);
        }
    }, 'json').fail(function() {
        showToast('An error occurred', 'error');
        $btn.prop('disabled', false).html(originalHTML);
    });
}

function respondToRequest(requestId, action, btn) {
    const $btn = $(btn);
    const originalHTML = $btn.html();
    $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
    
    $.post('<?= APP_URL ?>/friends/ajax/respond-request.php', {
        request_id: requestId,
        action: action
    }, function(response) {
        if (response.success) {
            showToast(response.message, 'success');
            $btn.closest('.col-lg-3').fadeOut(300, function() {
                $(this).remove();
                // Update count
                const count = $('.content-section#friend-requests .col-lg-3').length;
                $('.friends-header h4').text('Friend Requests (' + count + ')');
            });
        } else {
            showToast(response.message, 'error');
            $btn.prop('disabled', false).html(originalHTML);
        }
    }, 'json').fail(function() {
        showToast('An error occurred', 'error');
        $btn.prop('disabled', false).html(originalHTML);
    });
}

let unfriendId = null;

function showUnfriendModal(friendId, friendName) {
    unfriendId = friendId;
    $('#unfriendName').text(friendName);
    const modal = new bootstrap.Modal(document.getElementById('unfriendModal'));
    modal.show();
}

$('#confirmUnfriend').click(function() {
    if (!unfriendId) return;
    
    $.post('<?= APP_URL ?>/friends/ajax/unfriend.php', {
        friend_id: unfriendId
    }, function(response) {
        if (response.success) {
            showToast(response.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(response.message, 'error');
        }
        bootstrap.Modal.getInstance(document.getElementById('unfriendModal')).hide();
    }, 'json').fail(function() {
        showToast('An error occurred', 'error');
    });
});
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>