<?php
/**
 * Job Portal - Talent Showcase Page
 * GHAMECC Choir Management Platform
 * 
 * This page displays member profiles with search and filtering options.
 */

// Include database connection and functions
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

// Initialize variables
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 12;
$offset = ($page - 1) * $perPage;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$skills = isset($_GET['skills']) ? $_GET['skills'] : [];
$availability = isset($_GET['availability']) ? trim($_GET['availability']) : '';
$minRating = isset($_GET['min_rating']) ? (float)$_GET['min_rating'] : 0;
$sort = isset($_GET['sort']) ? trim($_GET['sort']) : 'rating_desc';

// Build the query
$query = "SELECT mp.*, m.first_name, m.last_name, m.email, m.phone, m.society_id,
          s.name as society_name, c.name as circuit_name, d.name as diocese_name,
          (SELECT AVG(rating) FROM member_ratings WHERE rated_id = mp.member_id) as avg_rating,
          (SELECT COUNT(*) FROM member_ratings WHERE rated_id = mp.member_id) as rating_count
          FROM member_profiles mp
          JOIN members m ON mp.member_id = m.id
          LEFT JOIN societies s ON m.society_id = s.id
          LEFT JOIN circuits c ON s.circuit_id = c.id
          LEFT JOIN dioceses d ON c.diocese_id = d.id
          WHERE 1=1";
$countQuery = "SELECT COUNT(*) FROM member_profiles mp JOIN members m ON mp.member_id = m.id WHERE 1=1";
$params = [];

// Add search condition
if (!empty($search)) {
    $searchTerm = "%$search%";
    $query .= " AND (m.first_name LIKE ? OR m.last_name LIKE ? OR mp.title LIKE ? OR mp.bio LIKE ? OR mp.skills LIKE ?)";
    $countQuery .= " AND (m.first_name LIKE ? OR m.last_name LIKE ? OR mp.title LIKE ? OR mp.bio LIKE ? OR mp.skills LIKE ?)";
    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm]);
}

// Add skills filter
if (!empty($skills)) {
    foreach ($skills as $skill) {
        $skillTerm = "%$skill%";
        $query .= " AND mp.skills LIKE ?";
        $countQuery .= " AND mp.skills LIKE ?";
        $params[] = $skillTerm;
    }
}

// Add availability filter
if (!empty($availability)) {
    $query .= " AND mp.availability = ?";
    $countQuery .= " AND mp.availability = ?";
    $params[] = $availability;
}

// Add minimum rating filter
if ($minRating > 0) {
    $query .= " HAVING avg_rating >= ?";
    $countQuery .= " AND mp.member_id IN (SELECT rated_id FROM member_ratings GROUP BY rated_id HAVING AVG(rating) >= ?)";
    $params[] = $minRating;
}

// Add sorting
switch ($sort) {
    case 'name_asc':
        $query .= " ORDER BY m.first_name ASC, m.last_name ASC";
        break;
    case 'name_desc':
        $query .= " ORDER BY m.first_name DESC, m.last_name DESC";
        break;
    case 'rating_asc':
        $query .= " ORDER BY avg_rating ASC";
        break;
    case 'newest':
        $query .= " ORDER BY mp.created_at DESC";
        break;
    case 'oldest':
        $query .= " ORDER BY mp.created_at ASC";
        break;
    case 'rating_desc':
    default:
        $query .= " ORDER BY avg_rating DESC";
        break;
}

// Add pagination
$query .= " LIMIT ? OFFSET ?";
$paginationParams = [$perPage, $offset];

// Get total count for pagination
$totalProfiles = fetchValue($countQuery, $params);
$totalPages = ceil($totalProfiles / $perPage);

// Get profiles
$profiles = fetchRows($query, array_merge($params, $paginationParams));

// Get all unique skills for filter dropdown
$allSkills = fetchRows("SELECT DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(mp.skills, ',', numbers.n), ',', -1) skill
                      FROM (SELECT 1 n UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) numbers
                      INNER JOIN member_profiles mp ON CHAR_LENGTH(mp.skills) - CHAR_LENGTH(REPLACE(mp.skills, ',', '')) >= numbers.n - 1
                      WHERE TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(mp.skills, ',', numbers.n), ',', -1)) != ''
                      ORDER BY skill");

// Page title
$pageTitle = "Talent Showcase | GHAMECC Job Portal";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom CSS -->
    <style>
        .profile-card {
            transition: transform 0.3s;
            height: 100%;
        }
        .profile-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .profile-image {
            height: 200px;
            object-fit: cover;
            border-top-left-radius: calc(0.375rem - 1px);
            border-top-right-radius: calc(0.375rem - 1px);
        }
        .filter-section {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .skill-badge {
            background-color: #e9ecef;
            color: #495057;
            padding: 0.35em 0.65em;
            border-radius: 0.25rem;
            margin-right: 0.25rem;
            margin-bottom: 0.25rem;
            display: inline-block;
            font-size: 0.75em;
            font-weight: 700;
            line-height: 1;
            text-align: center;
            white-space: nowrap;
            vertical-align: baseline;
        }
        .rating-stars {
            color: #ffc107;
        }
        .pagination-container {
            margin-top: 30px;
        }
        .availability-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            z-index: 10;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php include 'includes/job-portal-navbar.php'; ?>
    
    <div class="container py-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="mb-0">Talent Showcase</h1>
            <?php if (isLoggedIn()): ?>
                <a href="create-profile.php" class="btn btn-primary">
                    <i class="fas fa-user-plus me-2"></i> Create Your Profile
                </a>
            <?php endif; ?>
        </div>
        
        <!-- Filter Section -->
        <div class="filter-section">
            <form action="talent-showcase.php" method="get" class="row g-3">
                <div class="col-md-4">
                    <label for="search" class="form-label">Search</label>
                    <input type="text" class="form-control" id="search" name="search" placeholder="Name, title, skills..." value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="col-md-3">
                    <label for="skills" class="form-label">Skills</label>
                    <select class="form-select" id="skills" name="skills[]" multiple>
                        <?php foreach ($allSkills as $skillItem): ?>
                            <?php $skill = trim($skillItem['skill']); ?>
                            <option value="<?php echo htmlspecialchars($skill); ?>" <?php echo in_array($skill, $skills) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($skill); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="form-text text-muted">Hold Ctrl/Cmd to select multiple skills</small>
                </div>
                <div class="col-md-2">
                    <label for="availability" class="form-label">Availability</label>
                    <select class="form-select" id="availability" name="availability">
                        <option value="">All</option>
                        <option value="available" <?php echo $availability == 'available' ? 'selected' : ''; ?>>Available</option>
                        <option value="limited" <?php echo $availability == 'limited' ? 'selected' : ''; ?>>Limited</option>
                        <option value="unavailable" <?php echo $availability == 'unavailable' ? 'selected' : ''; ?>>Unavailable</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="min_rating" class="form-label">Minimum Rating</label>
                    <select class="form-select" id="min_rating" name="min_rating">
                        <option value="0" <?php echo $minRating == 0 ? 'selected' : ''; ?>>Any Rating</option>
                        <option value="1" <?php echo $minRating == 1 ? 'selected' : ''; ?>>1+ Stars</option>
                        <option value="2" <?php echo $minRating == 2 ? 'selected' : ''; ?>>2+ Stars</option>
                        <option value="3" <?php echo $minRating == 3 ? 'selected' : ''; ?>>3+ Stars</option>
                        <option value="4" <?php echo $minRating == 4 ? 'selected' : ''; ?>>4+ Stars</option>
                        <option value="4.5" <?php echo $minRating == 4.5 ? 'selected' : ''; ?>>4.5+ Stars</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="sort" class="form-label">Sort By</label>
                    <select class="form-select" id="sort" name="sort">
                        <option value="rating_desc" <?php echo $sort == 'rating_desc' ? 'selected' : ''; ?>>Highest Rated</option>
                        <option value="rating_asc" <?php echo $sort == 'rating_asc' ? 'selected' : ''; ?>>Lowest Rated</option>
                        <option value="name_asc" <?php echo $sort == 'name_asc' ? 'selected' : ''; ?>>Name (A-Z)</option>
                        <option value="name_desc" <?php echo $sort == 'name_desc' ? 'selected' : ''; ?>>Name (Z-A)</option>
                        <option value="newest" <?php echo $sort == 'newest' ? 'selected' : ''; ?>>Newest First</option>
                        <option value="oldest" <?php echo $sort == 'oldest' ? 'selected' : ''; ?>>Oldest First</option>
                    </select>
                </div>
                <div class="col-md-9 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary me-2">
                        <i class="fas fa-filter me-2"></i> Apply Filters
                    </button>
                    <a href="talent-showcase.php" class="btn btn-outline-secondary">
                        <i class="fas fa-redo me-2"></i> Reset
                    </a>
                </div>
            </form>
        </div>
        
        <!-- Results Summary -->
        <div class="mb-4">
            <p class="text-muted">
                Showing <?php echo count($profiles); ?> of <?php echo $totalProfiles; ?> profiles
                <?php if (!empty($search)): ?>
                    matching "<?php echo htmlspecialchars($search); ?>"
                <?php endif; ?>
                <?php if (!empty($skills)): ?>
                    with skills: <?php echo htmlspecialchars(implode(', ', $skills)); ?>
                <?php endif; ?>
                <?php if (!empty($availability)): ?>
                    who are <?php echo htmlspecialchars($availability); ?>
                <?php endif; ?>
                <?php if ($minRating > 0): ?>
                    with <?php echo $minRating; ?>+ star rating
                <?php endif; ?>
            </p>
        </div>
        
        <!-- Profile Listings -->
        <?php if (empty($profiles)): ?>
            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i> No profiles found matching your criteria. Try adjusting your filters.
            </div>
        <?php else: ?>
            <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
                <?php foreach ($profiles as $profile): ?>
                    <div class="col">
                        <div class="card profile-card">
                            <?php if ($profile['availability']): ?>
                                <div class="availability-badge">
                                    <span class="badge bg-<?php 
                                    switch($profile['availability']) {
                                        case 'available': echo 'success'; break;
                                        case 'limited': echo 'warning'; break;
                                        case 'unavailable': echo 'danger'; break;
                                        default: echo 'secondary';
                                    }
                                    ?>">
                                        <?php echo ucfirst($profile['availability']); ?>
                                    </span>
                                </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($profile['profile_image'])): ?>
                                <img src="<?php echo htmlspecialchars($profile['profile_image']); ?>" class="profile-image" alt="Profile Image">
                            <?php else: ?>
                                <img src="../assets/images/default-profile.jpg" class="profile-image" alt="Default Profile Image">
                            <?php endif; ?>
                            
                            <div class="card-body">
                                <h5 class="card-title">
                                    <a href="profile-details.php?id=<?php echo $profile['id']; ?>" class="text-decoration-none">
                                        <?php echo htmlspecialchars($profile['first_name'] . ' ' . $profile['last_name']); ?>
                                    </a>
                                </h5>
                                <h6 class="card-subtitle mb-2 text-muted"><?php echo htmlspecialchars($profile['title']); ?></h6>
                                
                                <div class="mb-2">
                                    <?php 
                                    $avgRating = $profile['avg_rating'] ? round($profile['avg_rating'] * 2) / 2 : 0;
                                    $ratingCount = $profile['rating_count'] ? $profile['rating_count'] : 0;
                                    ?>
                                    <div class="rating-stars">
                                        <?php for ($i = 1; $i <= 5; $i++): ?>
                                            <?php if ($i <= $avgRating): ?>
                                                <i class="fas fa-star"></i>
                                            <?php elseif ($i - 0.5 == $avgRating): ?>
                                                <i class="fas fa-star-half-alt"></i>
                                            <?php else: ?>
                                                <i class="far fa-star"></i>
                                            <?php endif; ?>
                                        <?php endfor; ?>
                                        <span class="text-muted ms-1">(<?php echo $ratingCount; ?>)</span>
                                    </div>
                                </div>
                                
                                <p class="card-text">
                                    <?php echo substr(htmlspecialchars($profile['bio']), 0, 100) . (strlen($profile['bio']) > 100 ? '...' : ''); ?>
                                </p>
                                
                                <?php if (!empty($profile['skills'])): ?>
                                    <div class="mb-3">
                                        <?php 
                                        $skillsArray = explode(',', $profile['skills']);
                                        $displaySkills = array_slice($skillsArray, 0, 3);
                                        foreach ($displaySkills as $skill): 
                                        ?>
                                            <span class="skill-badge"><?php echo htmlspecialchars(trim($skill)); ?></span>
                                        <?php endforeach; ?>
                                        <?php if (count($skillsArray) > 3): ?>
                                            <span class="skill-badge">+<?php echo count($skillsArray) - 3; ?> more</span>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="d-flex justify-content-between align-items-center mt-3">
                                    <small class="text-muted">
                                        <?php if (!empty($profile['society_name'])): ?>
                                            <i class="fas fa-church me-1"></i> <?php echo htmlspecialchars($profile['society_name']); ?>
                                        <?php endif; ?>
                                    </small>
                                    <a href="profile-details.php?id=<?php echo $profile['id']; ?>" class="btn btn-outline-primary btn-sm">
                                        View Profile
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
                <div class="pagination-container d-flex justify-content-center">
                    <nav aria-label="Page navigation">
                        <ul class="pagination">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=1<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($skills) ? '&skills[]=' . implode('&skills[]=', array_map('urlencode', $skills)) : ''; ?><?php echo !empty($availability) ? '&availability=' . urlencode($availability) : ''; ?><?php echo $minRating > 0 ? '&min_rating=' . $minRating : ''; ?><?php echo !empty($sort) ? '&sort=' . urlencode($sort) : ''; ?>" aria-label="First">
                                        <span aria-hidden="true">&laquo;&laquo;</span>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($skills) ? '&skills[]=' . implode('&skills[]=', array_map('urlencode', $skills)) : ''; ?><?php echo !empty($availability) ? '&availability=' . urlencode($availability) : ''; ?><?php echo $minRating > 0 ? '&min_rating=' . $minRating : ''; ?><?php echo !empty($sort) ? '&sort=' . urlencode($sort) : ''; ?>" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php
                            $startPage = max(1, $page - 2);
                            $endPage = min($totalPages, $page + 2);
                            
                            for ($i = $startPage; $i <= $endPage; $i++):
                            ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($skills) ? '&skills[]=' . implode('&skills[]=', array_map('urlencode', $skills)) : ''; ?><?php echo !empty($availability) ? '&availability=' . urlencode($availability) : ''; ?><?php echo $minRating > 0 ? '&min_rating=' . $minRating : ''; ?><?php echo !empty($sort) ? '&sort=' . urlencode($sort) : ''; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $totalPages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($skills) ? '&skills[]=' . implode('&skills[]=', array_map('urlencode', $skills)) : ''; ?><?php echo !empty($availability) ? '&availability=' . urlencode($availability) : ''; ?><?php echo $minRating > 0 ? '&min_rating=' . $minRating : ''; ?><?php echo !empty($sort) ? '&sort=' . urlencode($sort) : ''; ?>" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $totalPages; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($skills) ? '&skills[]=' . implode('&skills[]=', array_map('urlencode', $skills)) : ''; ?><?php echo !empty($availability) ? '&availability=' . urlencode($availability) : ''; ?><?php echo $minRating > 0 ? '&min_rating=' . $minRating : ''; ?><?php echo !empty($sort) ? '&sort=' . urlencode($sort) : ''; ?>" aria-label="Last">
                                        <span aria-hidden="true">&raquo;&raquo;</span>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
    
    <!-- Footer -->
    <footer class="bg-dark text-white py-4 mt-5">
        <div class="container">
            <div class="row">
                <div class="col-md-4 mb-4 mb-md-0">
                    <h5>GHAMECC Job Portal</h5>
                    <p class="text-muted">Connecting talent with opportunities within the GHAMECC community.</p>
                </div>
                <div class="col-md-4 mb-4 mb-md-0">
                    <h5>Quick Links</h5>
                    <ul class="list-unstyled">
                        <li><a href="index.php" class="text-decoration-none text-muted">Home</a></li>
                        <li><a href="job-listings.php" class="text-decoration-none text-muted">Job Listings</a></li>
                        <li><a href="categories.php" class="text-decoration-none text-muted">Categories</a></li>
                        <?php if (isLoggedIn()): ?>
                            <li><a href="create-profile.php" class="text-decoration-none text-muted">Create Profile</a></li>
                        <?php else: ?>
                            <li><a href="../login.php" class="text-decoration-none text-muted">Login</a></li>
                        <?php endif; ?>
                    </ul>
                </div>
                <div class="col-md-4">
                    <h5>Contact</h5>
                    <address class="text-muted">
                        <i class="fas fa-map-marker-alt me-2"></i> GHAMECC Headquarters<br>
                        <i class="fas fa-phone me-2"></i> (123) 456-7890<br>
                        <i class="fas fa-envelope me-2"></i> jobs@ghamecc.org
                    </address>
                </div>
            </div>
            <hr class="my-4 bg-secondary">
            <div class="text-center text-muted">
                <small>&copy; <?php echo date('Y'); ?> GHAMECC Job Portal. All rights reserved.</small>
            </div>
        </div>
    </footer>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
