<?php
require_once 'config.php';

$projects = getAllProjects($pdo);
$categories = $pdo->query("SELECT DISTINCT category FROM projects WHERE is_active = 1 ORDER BY category")->fetchAll(PDO::FETCH_COLUMN);
$selected_category = isset($_GET['category']) ? trim($_GET['category']) : '';

if($selected_category && $selected_category !== '') {
    $stmt = $pdo->prepare("SELECT * FROM projects WHERE is_active = 1 AND category = ? ORDER BY (goal_amount - current_amount) / goal_amount ASC, days_left ASC");
    $stmt->execute([$selected_category]);
    $projects = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Проекты для помощи - благотворительный фонд</title>
    <meta name="description" content="Проекты, которые нуждаются в вашей помощи. Поддержите тех, кому это действительно нужно.">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Arial, sans-serif; background: #f0fdf4; line-height: 1.6; }
        header, footer { background: #0f172a; color: #f8fafc; padding: 1rem; text-align: center; }
        nav a { color: #f8fafc; margin: 0 15px; text-decoration: none; transition: 0.3s; }
        nav a:hover { color: #14b8a6; }
        main { max-width: 1400px; margin: 30px auto; padding: 0 20px; min-height: 60vh; }
        h1 { text-align: center; color: #0f172a; margin-bottom: 10px; }
        .subtitle { text-align: center; color: #475569; margin-bottom: 30px; }
        
        .filter-section { background: #fff; padding: 20px; border-radius: 16px; margin-bottom: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .filter-title { font-size: 1.1rem; font-weight: bold; margin-bottom: 15px; color: #0f172a; }
        .filter-buttons { display: flex; flex-wrap: wrap; gap: 10px; }
        .filter-btn { background: #e2e8f0; color: #0f172a; border: none; padding: 8px 20px; border-radius: 30px; cursor: pointer; transition: 0.3s; text-decoration: none; display: inline-block; font-size: 0.9rem; }
        .filter-btn:hover { background: #cbd5e1; }
        .filter-btn.active { background: #0f766e; color: #fff; }
        .reset-btn { background: #64748b; color: #fff; }
        
        .projects-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(380px, 1fr)); gap: 30px; }
        .project-card { background: #fff; border-radius: 24px; overflow: hidden; box-shadow: 0 10px 30px rgba(0,0,0,0.08); transition: transform 0.3s; }
        .project-card:hover { transform: translateY(-5px); }
        .project-card img { width: 100%; height: 220px; object-fit: cover; }
        .project-info { padding: 25px; }
        .project-title { font-size: 1.4rem; font-weight: bold; color: #0f172a; margin-bottom: 10px; }
        .category-badge { display: inline-block; background: #e2e8f0; color: #475569; padding: 4px 12px; border-radius: 20px; font-size: 0.75rem; margin-bottom: 12px; }
        .description { color: #475569; margin: 12px 0; line-height: 1.5; }
        .location { color: #64748b; font-size: 0.85rem; margin-bottom: 15px; }
        .progress-section { margin: 20px 0; }
        .progress-stats { display: flex; justify-content: space-between; margin-bottom: 8px; font-size: 0.85rem; }
        .progress-bar { background: #e2e8f0; border-radius: 30px; height: 12px; overflow: hidden; }
        .progress-fill { background: linear-gradient(90deg, #0f766e, #14b8a6); width: 0%; height: 100%; border-radius: 30px; transition: width 0.5s ease; }
        .goal-info { font-size: 0.8rem; color: #64748b; margin-top: 8px; }
        .days-left { display: inline-block; background: #fef3c7; color: #d97706; padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; margin-bottom: 15px; }
        .btn { display: inline-block; background: #0f766e; color: #fff; padding: 12px 25px; text-decoration: none; border-radius: 40px; transition: 0.3s; font-weight: bold; margin-top: 15px; width: 100%; text-align: center; }
        .btn:hover { background: #0d5c56; transform: scale(1.02); }
        footer { margin-top: 50px; }
        .empty-message { text-align: center; padding: 50px; background: #fff; border-radius: 16px; }
        @media (max-width: 768px) { .projects-grid { grid-template-columns: 1fr; } .filter-buttons { justify-content: center; } }
    </style>
</head>
<body>
<header>
    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap;">
        <h1 style="margin: 0;">🤝 Благотворительный фонд "Вместе"</h1>
        <nav>
            <a href="index.php">🏠 Проекты</a>
            <a href="donate.php">💝 Пожертвовать</a>
            <a href="my_donations.php">📋 Мои пожертвования</a>
            <?php if(isLoggedIn()): ?>
                <a href="logout.php">🚪 Выйти (<?= h($_SESSION['username']) ?>)</a>
            <?php else: ?>
                <a href="login.php">🔐 Вход</a>
                <a href="register.php">📝 Регистрация</a>
            <?php endif; ?>
        </nav>
    </div>
</header>

<main>
    <h1>🤝 Проекты, которые ждут вашей помощи</h1>
    <p class="subtitle">Вместе мы можем изменить жизнь к лучшему</p>
    
    <div class="filter-section">
        <div class="filter-title">🔍 Фильтр по категории</div>
        <div class="filter-buttons">
            <a href="index.php" class="filter-btn <?= empty($selected_category) ? 'active' : '' ?>">Все проекты</a>
            <?php foreach($categories as $cat): ?>
                <a href="?category=<?= urlencode($cat) ?>" class="filter-btn <?= $selected_category == $cat ? 'active' : '' ?>">
                    <?= h($cat) ?>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
    
    <?php if(count($projects) > 0): ?>
        <div class="projects-grid">
            <?php foreach($projects as $project): 
                $percent = getProgressPercent($project['current_amount'], $project['goal_amount']);
                $need_amount = $project['goal_amount'] - $project['current_amount'];
            ?>
                <div class="project-card">
                    <img src="<?= h($project['image_url'] ?: 'img/placeholder.jpg') ?>" alt="<?= h($project['title']) ?>">
                    <div class="project-info">
                        <div class="project-title"><?= h($project['title']) ?></div>
                        <div><span class="category-badge">📁 <?= h($project['category']) ?></span></div>
                        <div class="description"><?= h(mb_substr($project['description'], 0, 100)) ?>...</div>
                        <div class="location">📍 <?= h($project['location']) ?></div>
                        <div class="days-left">⏰ Осталось дней: <?= $project['days_left'] ?></div>
                        
                        <div class="progress-section">
                            <div class="progress-stats">
                                <span>Собрано: <?= number_format($project['current_amount'], 0) ?> ₽</span>
                                <span><?= $percent ?>%</span>
                            </div>
                            <div class="progress-bar">
                                <div class="progress-fill" style="width: <?= $percent ?>%;"></div>
                            </div>
                            <div class="goal-info">
                                Нужно ещё: <?= number_format($need_amount, 0) ?> ₽ из <?= number_format($project['goal_amount'], 0) ?> ₽
                            </div>
                        </div>
                        
                        <a href="donate.php?project=<?= $project['id'] ?>" class="btn">💝 Пожертвовать</a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="empty-message">
            <p>😕 Проектов в выбранной категории не найдено.</p>
            <a href="index.php" class="filter-btn active">Показать все проекты</a>
        </div>
    <?php endif; ?>
</main>

<footer>
    <p>&copy; 2025 Благотворительный фонд "Вместе". Вместе мы сила!</p>
    <p>📍 Москва, ул. Доброты, 10 | 📞 8-800-555-35-35 | ✉️ info@vmeste.ru</p>
</footer>
</body>
</html>