<?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
$database = new Database();
$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, 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;
    }
    
    .profile-header {
        background: white;
        border-radius: 0 0 8px 8px;
        overflow: hidden;
        margin-bottom: 1rem;
    }
    
    .cover-photo {
        width: 100%;
        height: 350px;
        object-fit: cover;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    
    .profile-info-section {
        padding: 1.5rem;
        position: relative;
    }
    
    .profile-picture {
        width: 168px;
        height: 168px;
        border-radius: 50%;
        border: 4px solid white;
        object-fit: cover;
        position: absolute;
        top: -84px;
        left: 50%;
        transform: translateX(-50%);
        background: #f0f2f5;
    }
    
    .profile-name {
        margin-top: 100px;
        text-align: center;
    }
    
    .profile-name h1 {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 0.5rem;
    }
    
    .profile-stats {
        display: flex;
        justify-content: center;
        gap: 2rem;
        margin: 1rem 0;
        color: #65676b;
    }
    
    .profile-actions {
        display: flex;
        justify-content: center;
        gap: 0.75rem;
        padding: 1rem 0;
        border-top: 1px solid #e4e6eb;
    }
    
    .btn-fb {
        padding: 0.5rem 1.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;
    }
    
    .info-card {
        background: white;
        border-radius: 8px;
        padding: 1.5rem;
        margin-bottom: 1rem;
    }
    
    .info-card h5 {
        font-weight: 700;
        margin-bottom: 1rem;
    }
    
    .info-item {
        display: flex;
        align-items: center;
        padding: 0.75rem 0;
        gap: 1rem;
    }
    
    .info-item i {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f0f2f5;
        border-radius: 50%;
        font-size: 1.2rem;
        color: #65676b;
    }
    
    .mutual-friends-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 0.5rem;
    }
    
    .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: 50%;
        object-fit: cover;
        margin-bottom: 0.5rem;
    }
    
    .mutual-friend-item .name {
        font-size: 0.75rem;
        color: #050505;
    }
    
    .post-card {
        background: white;
        border-radius: 8px;
        padding: 1.5rem;
        margin-bottom: 1rem;
    }
    
    .privacy-notice {
        background: #fff3cd;
        border-left: 4px solid #ffc107;
        padding: 1rem;
        border-radius: 4px;
        margin-bottom: 1rem;
    }
</style>

<div class="profile-container">
    <div class="container py-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">
            <?php else: ?>
                <div class="cover-photo"></div>
            <?php endif; ?>
            
            <div class="profile-info-section">
                <img src="<?= APP_URL . '/' . htmlspecialchars($profile['profile_picture']) ?>" 
                     alt="<?= htmlspecialchars($profile['full_name']) ?>" 
                     class="profile-picture">
                
                <div class="profile-name">
                    <h1><?= htmlspecialchars($profile['full_name']) ?></h1>
                    <?php if ($profile['tagline']): ?>
                        <p class="text-muted"><?= 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 Friends
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="profile-actions">
                    <?php if ($isOwnProfile): ?>
                        <a href="../profile/edit.php" class="btn-fb btn-primary-fb">
                            <i class="bi bi-pencil"></i> Edit Profile
                        </a>
                    <?php else: ?>
                        <?php if ($isFriend): ?>
                            <button class="btn-fb btn-secondary-fb">
                                <i class="bi bi-check-circle-fill"></i> Friends
                            </button>
                            <a href="../chat/one-on-one.php?user_id=<?= $profileId ?>" class="btn-fb btn-primary-fb">
                                <i class="bi bi-messenger"></i> Message
                            </a>
                        <?php elseif ($friendshipStatus && $friendshipStatus['status'] === 'pending'): ?>
                            <button class="btn-fb btn-secondary-fb" disabled>
                                <i class="bi bi-clock"></i> Request Pending
                            </button>
                        <?php else: ?>
                            <button class="btn-fb btn-primary-fb" onclick="sendFriendRequest(<?= $profileId ?>, this)">
                                <i class="bi bi-person-plus"></i> Add Friend
                            </button>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </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>
                                From <strong><?= htmlspecialchars($profile['district_name'] ?? 'Unknown') ?></strong>
                                <?php if ($profile['subcounty_name']): ?>
                                    <div class="text-muted small"><?= htmlspecialchars($profile['subcounty_name']) ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($profile['show_phone'] && ($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']) ?>">
                                    <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>
                    </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 Pending').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);
    });
}
</script>

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