<?php
session_start();
require 'config.php';

$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    header("Location: ?view=login");
    exit;
}

// Get target user ID
$target_id = $_GET['id'] ?? $user_id;

// Fetch profile user
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$target_id]);
$profile_user = $stmt->fetch();

if (!$profile_user) {
    die("User not found");
}

// Check if following
$stmt = $pdo->prepare("SELECT * FROM follows WHERE follower_id = ? AND following_id = ?");
$stmt->execute([$user_id, $target_id]);
$is_following = $stmt->fetch() ? true : false;

// Get stats
$stmt = $pdo->prepare("SELECT COUNT(*) FROM posts WHERE user_id = ?");
$stmt->execute([$target_id]);
$posts_count = $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM follows WHERE following_id = ?");
$stmt->execute([$target_id]);
$followers_count = $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM follows WHERE follower_id = ?");
$stmt->execute([$target_id]);
$following_count = $stmt->fetchColumn();

// Get posts
$stmt = $pdo->prepare("SELECT * FROM posts WHERE user_id = ? AND type = 'post' ORDER BY created_at DESC");
$stmt->execute([$target_id]);
$profile_posts = $stmt->fetchAll();

$is_own_profile = ($target_id == $user_id);
?>
<!DOCTYPE html>
<html lang="uk">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($profile_user['username']); ?> - UAgram</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
    <div class="profile-container" style="max-width: 935px; margin: 0 auto; padding: 30px 20px;">
        <!-- Profile Header -->
        <header class="profile-header" style="display: flex; margin-bottom: 44px; align-items: center;">
            <div style="flex: 0 0 auto; margin-right: 30px;">
                <img src="<?php echo !empty($profile_user['avatar']) ? htmlspecialchars($profile_user['avatar']) : 'assets/default_avatar.svg'; ?>" 
                     style="width: 150px; height: 150px; border-radius: 50%; object-fit: cover;">
            </div>
            
            <div style="flex: 1;">
                <div style="display: flex; align-items: center; margin-bottom: 20px;">
                    <h2 style="font-size: 28px; font-weight: 300; margin: 0 20px 0 0;"><?php echo htmlspecialchars($profile_user['username']); ?></h2>
                    
                    <?php if ($is_own_profile): ?>
                        <a href="settings.php" class="btn-secondary" style="padding: 7px 16px; margin-right: 8px;">Редагувати профіль</a>
                        <button class="btn-secondary" style="padding: 7px 16px;">Переглянути архів</button>
                    <?php else: ?>
                        <button id="follow-btn" onclick="toggleFollow(<?php echo $target_id; ?>)" 
                                class="<?php echo $is_following ? 'btn-secondary' : 'btn-primary'; ?>" 
                                style="padding: 7px 24px; margin-right: 8px;">
                            <?php echo $is_following ? 'Ви стежите' : 'Стежити'; ?>
                        </button>
                        <button onclick="startConversation(<?php echo $target_id; ?>)" class="btn-secondary" style="padding: 7px 24px; margin-right: 8px;">Надіслати повідомлення</button>
                        <button class="btn-secondary" style="padding: 7px 16px;">▼</button>
                    <?php endif; ?>
                </div>
                
                <div class="profile-stats" style="display: flex; margin-bottom: 20px; font-size: 16px;">
                    <span style="margin-right: 40px;"><strong><?php echo $posts_count; ?></strong> дописів</span>
                    <span style="margin-right: 40px; cursor: pointer;" onclick="showFollowers(<?php echo $target_id; ?>)">
                        <strong><?php echo $followers_count; ?></strong> читачів
                    </span>
                    <span style="cursor: pointer;" onclick="showFollowing(<?php echo $target_id; ?>)">
                        <strong><?php echo $following_count; ?></strong> стежить
                    </span>
                </div>
                
                <div style="font-weight: 600; margin-bottom: 4px;"><?php echo htmlspecialchars($profile_user['full_name']); ?></div>
                <?php if (!empty($profile_user['bio'])): ?>
                    <div style="white-space: pre-wrap;"><?php echo htmlspecialchars($profile_user['bio']); ?></div>
                <?php endif; ?>
            </div>
        </header>
        
        <!-- Profile Tabs -->
        <div style="border-top: 1px solid var(--border-color); display: flex; justify-content: center; gap: 60px;">
            <div class="profile-tab active" onclick="switchProfileTab('posts', this)" style="padding: 18px 0; border-top: 1px solid white; margin-top: -1px; display: flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 600; letter-spacing: 1px; cursor: pointer;">
                <svg fill="currentColor" height="12" viewBox="0 0 24 24" width="12"><rect fill="none" height="18" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" width="18" x="3" y="3"></rect><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="9.015" x2="9.015" y1="3" y2="21"></line><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="14.985" x2="14.985" y1="3" y2="21"></line><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="21" x2="3" y1="9.015" y2="9.015"></line><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="21" x2="3" y1="14.985" y2="14.985"></line></svg>
                ДОПИСИ
            </div>
            <div class="profile-tab" onclick="switchProfileTab('reels', this)" style="padding: 18px 0; display: flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 600; letter-spacing: 1px; cursor: pointer; color: var(--text-secondary);">
                <svg fill="currentColor" height="12" viewBox="0 0 24 24" width="12"><path d="M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.6 0 12 0zm0 22C6.5 22 2 17.5 2 12S6.5 2 12 2s10 4.5 10 10-4.5 10-10 10z"></path><path d="M12 6c-3.3 0-6 2.7-6 6s2.7 6 6 6 6-2.7 6-6-2.7-6-6-6zm0 10c-2.2 0-4-1.8-4-4s1.8-4 4-4 4 1.8 4 4-1.8 4-4 4z"></path></svg>
                REELS
            </div>
            <?php if ($is_own_profile): ?>
            <div class="profile-tab" onclick="switchProfileTab('saved', this)" style="padding: 18px 0; display: flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 600; letter-spacing: 1px; cursor: pointer; color: var(--text-secondary);">
                <svg fill="currentColor" height="12" viewBox="0 0 24 24" width="12"><polygon fill="none" points="20 21 12 13.44 4 21 4 3 20 3 20 21" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></polygon></svg>
                ЗБЕРЕЖЕНО
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Posts Grid -->
        <div class="profile-grid" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; margin-top: 20px;">
            <?php if (empty($profile_posts)): ?>
                <div style="grid-column: 1 / -1; text-align: center; padding: 60px 0; color: var(--text-secondary);">
                    <svg aria-label="Камера" fill="currentColor" height="62" viewBox="0 0 96 96" width="62"><circle cx="48" cy="48" fill="none" r="47" stroke="currentColor" stroke-miterlimit="10" stroke-width="2"></circle><ellipse cx="48.002" cy="49.524" fill="none" rx="10.444" ry="10.476" stroke="currentColor" stroke-linejoin="round" stroke-width="2.095"></ellipse><path d="M63.994 69A8.02 8.02 0 0 0 72 60.968V39.456a8.023 8.023 0 0 0-8.01-8.035h-1.749a4.953 4.953 0 0 1-4.591-3.242C56.61 25.696 54.859 25 52.469 25h-8.983c-2.39 0-4.141.695-5.181 3.178a4.954 4.954 0 0 1-4.592 3.242H32.01a8.024 8.024 0 0 0-8.012 8.035v21.512A8.02 8.02 0 0 0 32.007 69Z" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="2"></path></svg>
                    <p style="margin-top: 20px; font-size: 28px; font-weight: 300;">Поки немає дописів</p>
                </div>
            <?php else: ?>
                <?php foreach ($profile_posts as $post): ?>
                    <div class="grid-post" onclick="openPostModal(<?php echo $post['id']; ?>)" style="aspect-ratio: 1; overflow: hidden; cursor: pointer; position: relative;">
                        <?php if ($post['media_type'] === 'video'): ?>
                            <video src="<?php echo htmlspecialchars($post['image_url']); ?>" style="width: 100%; height: 100%; object-fit: cover;"></video>
                        <?php else: ?>
                            <img src="<?php echo htmlspecialchars($post['image_url']); ?>" style="width: 100%; height: 100%; object-fit: cover;">
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
    
    <script src="assets/app.js"></script>
    <script>
        const profileUserId = <?php echo $target_id; ?>;

        function toggleFollow(userId) {
            const btn = document.getElementById('follow-btn');
            const formData = new FormData();
            formData.append('action', 'follow');
            formData.append('user_id', userId);
            
            fetch('api.php', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    if (data.following) {
                        btn.textContent = 'Ви стежите';
                        btn.className = 'btn-secondary';
                    } else {
                        btn.textContent = 'Стежити';
                        btn.className = 'btn-primary';
                    }
                    // Update followers count
                    location.reload();
                }
            });
        }
        
        function startConversation(userId) {
            const formData = new FormData();
            formData.append('action', 'start_conversation');
            formData.append('user_id', userId);
            
            fetch('api.php', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    // Redirect to direct messages with conversation ID
                    window.location.href = `?view=direct&conv=${data.conversation_id}`;
                } else {
                    alert('Помилка створення розмови');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Помилка з\'єднання');
            });
        }
        
        function showFollowers(userId) {
            alert('Список читачів - функція в розробці');
        }
        
        function showFollowing(userId) {
            alert('Список підписок - функція в розробці');
        }
    </script>
</body>
</html>
