<?php
/**
 * ============================================================================
 * friends/profile.php - View Friend Profile
 * ============================================================================
 * Facebook-style profile viewing with privacy controls
 */

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

requireLogin();

$userId = getUserId();
$profileId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if (!$profileId) {
    redirect('/friends/index.php');
}

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

// Get user profile with proper image paths
$profile = $friendshipClass->getUserProfile($profileId);

if (!$profile) {
    redirect('/friends/index.php');
}

// Check friendship status
$friendshipStatus = $friendshipClass->getStatus($userId, $profileId);
$isFriend = $friendshipStatus && $friendshipStatus['status'] === 'accepted';
$isOwnProfile = $userId === $profileId;

// Get mutual friends
$mutualFriends = $friendshipClass->getMutualFriends($userId, $profileId);

// Get user's posts (if allowed)
$posts = [];
if ($isOwnProfile || $isFriend || $profile['profile_visibility'] === 'public') {
    $postClass = new \App\Post($db);
    $posts = $postClass->getUserPosts($profileId, $userId, 10);
}

$pageTitle = $profile['full_name'];
include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<style>
    .profile-container {
        background: #f0f2f5;
        min-height: 100vh;
        padding-top: 0;
    }
    
    .profile-header {
        background: white;
        border-radius: 0 0 8px 8px;
        overflow: visible;
        margin-bottom: 1rem;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
    }
    
    .cover-photo {
        width: 100%;
        height: 300px;
        object-fit: cover;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    
    @media (max-width: 768px) {
        .cover-photo {
            height: 200px;
        }
    }
    
    .profile-info-section {
        padding: 0 1rem 1rem;
        position: relative;
    }
    
    .profile-picture-wrapper {
        position: relative;
        margin-top: -80px;
        padding: 0 1rem;
        margin-bottom: 1rem;
        display: flex;
        justify-content: center;
    }
    
    .profile-picture {
        width: 168px;
        height: 168px;
        border-radius: 50%;
        border: 5px solid white;
        object-fit: cover;
        background: #e4e6eb;
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    }
    
    @media (max-width: 768px) {
        .profile-picture {
            width: 120px;
            height: 120px;
        }
        .profile-picture-wrapper {
            margin-top: -60px;
        }
    }
    
    .online-indicator {
        position: absolute;
        bottom: 15px;
        right: calc(50% - 70px);
        width: 24px;
        height: 24px;
        background: #31a24c;
        border: 4px solid white;
        border-radius: 50%;
    }
    
    @media (max-width: 768px) {
        .online-indicator {
            bottom: 10px;
            right: calc(50% - 50px);
            width: 18px;
            height: 18px;
            border: 3px solid white;
        }
    }
    
    .profile-name {
        text-align: center;
        padding-top: 0.5rem;
    }
    
    .profile-name h1 {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 0.25rem;
    }
    
    @media (max-width: 768px) {
        .profile-name h1 {
            font-size: 1.5rem;
        }
    }
    
    .profile-stats {
        display: flex;
        justify-content: center;
        gap: 1.5rem;
        margin: 1rem 0;
        color: #65676b;
        font-size: 0.9rem;
    }
    
    .profile-actions {
        display: flex;
        justify-content: center;
        gap: 0.75rem;
        padding: 1rem 0;
        border-top: 1px solid #e4e6eb;
        flex-wrap: wrap;
    }
    
    .btn-fb {
        padding: 0.5rem 1.5rem;
        border-radius: 6px;
        font-weight: 600;
        font-size: 0.9rem;
        border: none;
        cursor: pointer;
        transition: all 0.2s;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        text-decoration: none;
    }
    
    .btn-primary-fb {
        background: #1877f2;
        color: white;
    }
    
    .btn-primary-fb:hover {
        background: #166fe5;
        color: white;
    }
    
    .btn-secondary-fb {
        background: #e4e6eb;
        color: #050505;
    }
    
    .btn-secondary-fb:hover {
        background: #d8dadf;
        color: #050505;
    }
    
    .btn-more {
        width: 36px;
        height: 36px;
        border-radius: 6px;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .info-card {
        background: white;
        border-radius: 8px;
        padding: 1.5rem;
        margin-bottom: 1rem;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
    }
    
    .info-card h5 {
        font-weight: 700;
        margin-bottom: 1rem;
        font-size: 1.1rem;
    }
    
    .info-item {
        display: flex;
        align-items: center;
        padding: 0.75rem 0;
        gap: 1rem;
    }
    
    .info-item i {
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f0f2f5;
        border-radius: 50%;
        font-size: 1rem;
        color: #65676b;
        flex-shrink: 0;
    }
    
    .mutual-friends-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 0.75rem;
    }
    
    @media (max-width: 768px) {
        .mutual-friends-grid {
            grid-template-columns: repeat(2, 1fr);
        }
    }
    
    .mutual-friend-item {
        text-align: center;
        cursor: pointer;
        padding: 0.5rem;
        border-radius: 8px;
        transition: background 0.2s;
    }
    
    .mutual-friend-item:hover {
        background: #f0f2f5;
    }
    
    .mutual-friend-item img {
        width: 60px;
        height: 60px;
        border-radius: 8px;
        object-fit: cover;
        margin-bottom: 0.5rem;
    }
    
    .mutual-friend-item .name {
        font-size: 0.75rem;
        color: #050505;
        font-weight: 500;
        display: block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    .post-card {
        background: white;
        border-radius: 8px;
        padding: 1rem;
        margin-bottom: 1rem;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
    }
    
    .post-header {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        margin-bottom: 1rem;
    }
    
    .post-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        object-fit: cover;
        flex-shrink: 0;
    }
    
    .post-images {
        display: grid;
        gap: 4px;
        margin: 1rem 0;
        border-radius: 8px;
        overflow: hidden;
    }
    
    .post-images.single {
        grid-template-columns: 1fr;
    }
    
    .post-images.double {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .post-images.multiple {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .post-images img {
        width: 100%;
        height: 250px;
        object-fit: cover;
        cursor: pointer;
    }
    
    .post-images.single img {
        height: 400px;
        max-height: 500px;
    }
    
    @media (max-width: 768px) {
        .post-images img {
            height: 180px;
        }
        .post-images.single img {
            height: 300px;
        }
    }
    
    .post-actions {
        display: flex;
        justify-content: space-around;
        padding: 0.5rem 0;
        border-top: 1px solid #e4e6eb;
        margin-top: 0.75rem;
    }
    
    .post-action-btn {
        background: none;
        border: none;
        color: #65676b;
        cursor: pointer;
        padding: 0.5rem 1rem;
        transition: background 0.2s;
        border-radius: 6px;
        font-weight: 600;
        font-size: 0.9rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    
    .post-action-btn:hover {
        background: #f0f2f5;
    }
    
    .post-action-btn.liked {
        color: #f02849;
    }
    
    .post-action-btn.liked i {
        color: #f02849;
    }
    
    .post-stats {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.5rem 0;
        font-size: 0.85rem;
        color: #65676b;
    }
    
    .privacy-notice {
        background: #fff3cd;
        border-left: 4px solid #ffc107;
        padding: 1rem;
        border-radius: 4px;
        margin-bottom: 1rem;
    }
    
    .tab-navigation {
        background: white;
        border-radius: 8px;
        margin-bottom: 1rem;
        padding: 0 1rem;
        display: flex;
        gap: 1rem;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
    }
    
    .tab-link {
        padding: 1rem 0.5rem;
        color: #65676b;
        text-decoration: none;
        font-weight: 600;
        border-bottom: 3px solid transparent;
        transition: all 0.2s;
    }
    
    .tab-link:hover {
        color: #1877f2;
    }
    
    .tab-link.active {
        color: #1877f2;
        border-bottom-color: #1877f2;
    }
</style>

<div class="profile-container">
    <div class="container py-0 py-md-4">
        <!-- Profile Header -->
        <div class="profile-header">
            <?php if ($profile['cover_photo']): ?>
                <img src="<?= APP_URL . '/' . htmlspecialchars($profile['cover_photo']) ?>" 
                     alt="Cover" 
                     class="cover-photo"
                     onerror="this.src='<?= APP_URL ?>/assets/images/default-cover.jpg'">
            <?php else: ?>
                <div class="cover-photo"></div>
            <?php endif; ?>
            
            <div class="profile-info-section">
                <div class="profile-picture-wrapper">
                    <img src="<?= APP_URL . '/' . htmlspecialchars($profile['profile_picture']) ?>" 
                         alt="<?= htmlspecialchars($profile['full_name']) ?>" 
                         class="profile-picture"
                         onerror="this.src='<?= APP_URL ?>/assets/images/default-avatar.png'">
                    <?php if (!$isOwnProfile && $isFriend): ?>
                        <?php
                        // Check if friend is online (last activity within 5 minutes)
                        $isOnline = false;
                        if (isset($profile['last_activity'])) {
                            $lastActivity = strtotime($profile['last_activity']);
                            $isOnline = (time() - $lastActivity) < 300; // 5 minutes
                        }
                        ?>
                        <?php if ($isOnline): ?>
                            <span class="online-indicator"></span>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
                
                <div class="profile-name">
                    <h1><?= htmlspecialchars($profile['full_name']) ?></h1>
                    <?php if ($profile['tagline']): ?>
                        <p class="text-muted mb-0"><?= htmlspecialchars($profile['tagline']) ?></p>
                    <?php endif; ?>
                </div>
                
                <div class="profile-stats">
                    <div>
                        <strong><?= $profile['posts_count'] ?></strong> Posts
                    </div>
                    <div>
                        <strong><?= $profile['friends_count'] ?></strong> Friends
                    </div>
                    <?php if (count($mutualFriends) > 0 && !$isOwnProfile): ?>
                        <div>
                            <strong><?= count($mutualFriends) ?></strong> Mutual
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="profile-actions">
                    <?php if ($isOwnProfile): ?>
                        <a href="<?= APP_URL ?>/profile/edit.php" class="btn-fb btn-primary-fb">
                            <i class="bi bi-pencil"></i> Edit Profile
                        </a>
                        <button class="btn-fb btn-secondary-fb">
                            <i class="bi bi-eye"></i> View As
                        </button>
                    <?php else: ?>
                        <?php if ($isFriend): ?>
                            <button class="btn-fb btn-secondary-fb">
                                <i class="bi bi-person-check-fill"></i> Friends
                            </button>
                            <a href="<?= APP_URL ?>/chat/one-on-one.php?friend_id=<?= $profileId ?>" class="btn-fb btn-primary-fb">
                                <i class="bi bi-messenger"></i> Message
                            </a>
                            <button class="btn-fb btn-secondary-fb btn-more" title="More">
                                <i class="bi bi-three-dots"></i>
                            </button>
                        <?php elseif ($friendshipStatus && $friendshipStatus['status'] === 'pending'): ?>
                            <?php if ($friendshipStatus['direction'] === 'sent'): ?>
                                <button class="btn-fb btn-secondary-fb" disabled>
                                    <i class="bi bi-clock"></i> Request Sent
                                </button>
                            <?php else: ?>
                                <button class="btn-fb btn-primary-fb" onclick="respondToRequest(<?= $friendshipStatus['id'] ?>, 'accept', this)">
                                    <i class="bi bi-person-check"></i> Confirm Request
                                </button>
                                <button class="btn-fb btn-secondary-fb" onclick="respondToRequest(<?= $friendshipStatus['id'] ?>, 'reject', this)">
                                    <i class="bi bi-x"></i> Delete Request
                                </button>
                            <?php endif; ?>
                        <?php else: ?>
                            <button class="btn-fb btn-primary-fb" onclick="sendFriendRequest(<?= $profileId ?>, this)">
                                <i class="bi bi-person-plus"></i> Add Friend
                            </button>
                            <button class="btn-fb btn-secondary-fb btn-more" title="More">
                                <i class="bi bi-three-dots"></i>
                            </button>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Tab Navigation -->
        <div class="tab-navigation">
            <a href="#" class="tab-link active">
                <i class="bi bi-file-text"></i> Posts
            </a>
            <a href="#" class="tab-link">
                <i class="bi bi-images"></i> Photos
            </a>
            <a href="#" class="tab-link">
                <i class="bi bi-people"></i> Friends
            </a>
            <?php if ($isOwnProfile || $isFriend || $profile['profile_visibility'] === 'public'): ?>
                <a href="#" class="tab-link">
                    <i class="bi bi-info-circle"></i> About
                </a>
            <?php endif; ?>
        </div>
        
        <div class="row">
            <!-- Sidebar -->
            <div class="col-lg-5">
                <!-- About -->
                <div class="info-card">
                    <h5>About</h5>
                    
                    <?php if ($profile['bio']): ?>
                        <p><?= nl2br(htmlspecialchars($profile['bio'])) ?></p>
                        <hr>
                    <?php endif; ?>
                    
                    <div class="info-item">
                        <i class="bi bi-briefcase-fill"></i>
                        <div>
                            <strong><?= ucfirst(str_replace('_', ' ', $profile['user_type'])) ?></strong>
                            <?php if ($profile['occupation']): ?>
                                <div class="text-muted small"><?= htmlspecialchars($profile['occupation']) ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <?php if ($profile['show_location'] || $isOwnProfile || $isFriend): ?>
                        <div class="info-item">
                            <i class="bi bi-geo-alt-fill"></i>
                            <div>
                                <?php if ($profile['district_name']): ?>
                                    From <strong><?= htmlspecialchars($profile['district_name']) ?></strong>
                                    <?php if ($profile['subcounty_name']): ?>
                                        <div class="text-muted small"><?= htmlspecialchars($profile['subcounty_name']) ?></div>
                                    <?php endif; ?>
                                <?php else: ?>
                                    Location not set
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($profile['show_phone'] && $profile['phone_number'] && ($isOwnProfile || $isFriend)): ?>
                        <div class="info-item">
                            <i class="bi bi-telephone-fill"></i>
                            <div>
                                <a href="tel:<?= htmlspecialchars($profile['phone_number']) ?>">
                                    <?= htmlspecialchars($profile['phone_number']) ?>
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($profile['show_email'] && $profile['email'] && ($isOwnProfile || $isFriend)): ?>
                        <div class="info-item">
                            <i class="bi bi-envelope-fill"></i>
                            <div>
                                <a href="mailto:<?= htmlspecialchars($profile['email']) ?>">
                                    <?= htmlspecialchars($profile['email']) ?>
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <div class="info-item">
                        <i class="bi bi-calendar-event"></i>
                        <div class="text-muted small">
                            Joined <?= date('F Y', strtotime($profile['created_at'])) ?>
                        </div>
                    </div>
                </div>
                
                <!-- Mutual Friends -->
                <?php if (count($mutualFriends) > 0 && !$isOwnProfile): ?>
                    <div class="info-card">
                        <h5>Mutual Friends (<?= count($mutualFriends) ?>)</h5>
                        <div class="mutual-friends-grid">
                            <?php foreach (array_slice($mutualFriends, 0, 9) as $mutual): ?>
                                <div class="mutual-friend-item" 
                                     onclick="window.location.href='profile.php?id=<?= $mutual['id'] ?>'">
                                    <img src="<?= APP_URL . '/' . htmlspecialchars($mutual['profile_picture']) ?>" 
                                         alt="<?= htmlspecialchars($mutual['full_name']) ?>"
                                         onerror="this.src='<?= APP_URL ?>/assets/images/default-avatar.png'">
                                    <div class="name"><?= htmlspecialchars($mutual['full_name']) ?></div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <?php if (count($mutualFriends) > 9): ?>
                            <a href="mutual-friends.php?id=<?= $profileId ?>" class="btn btn-link mt-2">
                                See all mutual friends
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Posts -->
            <div class="col-lg-7">
                <h5 class="mb-3" style="font-weight: 700;">Posts</h5>
                
                <?php if (!$isOwnProfile && !$isFriend && $profile['profile_visibility'] !== 'public'): ?>
                    <div class="privacy-notice">
                        <i class="bi bi-lock-fill"></i> 
                        You must be friends with <?= htmlspecialchars(explode(' ', $profile['full_name'])[0]) ?> 
                        to see their posts.
                    </div>
                <?php elseif (empty($posts)): ?>
                    <div class="info-card text-center py-5">
                        <i class="bi bi-file-post" style="font-size: 3rem; color: #d8dadf;"></i>
                        <h5 class="mt-3">No Posts Yet</h5>
                        <?php if ($isOwnProfile): ?>
                            <p class="text-muted">Share your first post!</p>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <?php foreach ($posts as $post): ?>
                        <?php include __DIR__ . '/../posts/post-card.php'; ?>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
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) {
            $btn.html('<i class="bi bi-clock"></i> Request Sent')
                .removeClass('btn-primary-fb')
                .addClass('btn-secondary-fb');
        } else {
            alert(response.message);
            $btn.prop('disabled', false).html(originalHTML);
        }
    }, 'json').fail(function() {
        alert('An error occurred');
        $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) {
            if (action === 'accept') {
                location.reload();
            } else {
                $btn.parent().html('<button class="btn-fb btn-primary-fb" onclick="sendFriendRequest(<?= $profileId ?>, this)"><i class="bi bi-person-plus"></i> Add Friend</button>');
            }
        } else {
            alert(response.message);
            $btn.prop('disabled', false).html(originalHTML);
        }
    }, 'json').fail(function() {
        alert('An error occurred');
        $btn.prop('disabled', false).html(originalHTML);
    });
}
</script>

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