<?php
/**
 * Job Portal - Profile Details Page
 * GHAMECC Choir Management Platform
 * 
 * This page displays detailed information about a member's profile.
 */

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

// Check if profile ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: talent-showcase.php');
    exit;
}

$profileId = (int)$_GET['id'];

// Get profile details
$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 mp.id = ?";

$profile = fetchRow($query, [$profileId]);

// If profile doesn't exist, redirect
if (!$profile) {
    header('Location: talent-showcase.php');
    exit;
}

// Check if current user is the profile owner
$isProfileOwner = false;
$currentMemberId = null;
if (isLoggedIn()) {
    $currentUserId = $_SESSION['user_id'];
    $memberQuery = "SELECT id FROM members WHERE user_id = ?";
    $currentMemberId = fetchValue($memberQuery, [$currentUserId]);
    
    if ($currentMemberId && $currentMemberId == $profile['member_id']) {
        $isProfileOwner = true;
    }
}

// Get member ratings and reviews
$ratingsQuery = "SELECT mr.*, m.first_name, m.last_name, j.title as job_title
                FROM member_ratings mr
                JOIN members m ON mr.rater_id = m.id
                LEFT JOIN jobs j ON mr.job_id = j.id
                WHERE mr.rated_id = ?
                ORDER BY mr.created_at DESC";

$ratings = fetchRows($ratingsQuery, [$profile['member_id']]);

// Get completed jobs
$jobsQuery = "SELECT j.*, ja.status as application_status
             FROM jobs j
             JOIN job_applications ja ON j.id = ja.job_id
             WHERE ja.member_id = ? AND ja.status = 'selected'
             ORDER BY j.created_at DESC
             LIMIT 5";

$completedJobs = fetchRows($jobsQuery, [$profile['member_id']]);

// Check if the current user has already rated this profile
$hasRated = false;
if ($currentMemberId) {
    $ratingCheckQuery = "SELECT id FROM member_ratings WHERE rater_id = ? AND rated_id = ?";
    $hasRated = fetchValue($ratingCheckQuery, [$currentMemberId, $profile['member_id']]) ? true : false;
}

// Page title
$pageTitle = htmlspecialchars($profile['first_name'] . ' ' . $profile['last_name']) . " - Profile | GHAMECC Job Portal";

// Display success message if set
$successMessage = isset($_SESSION['success']) ? $_SESSION['success'] : '';
if (isset($_SESSION['success'])) {
    unset($_SESSION['success']);
}

// Display error message if set
$errorMessage = isset($_SESSION['error']) ? $_SESSION['error'] : '';
if (isset($_SESSION['error'])) {
    unset($_SESSION['error']);
}
?>
<!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">
    <!-- Lightbox CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css" rel="stylesheet">
    <style>
        .profile-header {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 30px;
            margin-bottom: 30px;
        }
        .profile-image {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid #fff;
            box-shadow: 0 0 15px rgba(0,0,0,0.1);
        }
        .rating-stars {
            color: #ffc107;
            font-size: 1.2rem;
        }
        .skill-badge {
            background-color: #e9ecef;
            color: #495057;
            border-radius: 20px;
            padding: 5px 15px;
            margin: 5px;
            display: inline-block;
        }
        .section-title {
            border-bottom: 2px solid #0d6efd;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        .review-card {
            border-left: 4px solid #0d6efd;
        }
        .availability-badge {
            font-size: 0.9rem;
            padding: 5px 10px;
        }
        .contact-btn {
            border-radius: 30px;
            padding: 8px 25px;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php include 'includes/navbar.php'; ?>

    <!-- Main Content -->
    <div class="container py-5">
        <?php if (!empty($successMessage)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $successMessage; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($errorMessage)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $errorMessage; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <!-- Profile Header -->
        <div class="profile-header">
            <div class="row align-items-center">
                <div class="col-md-3 text-center">
                    <?php if (!empty($profile['resume_path'])): ?>
                        <img src="../<?php echo $profile['resume_path']; ?>" alt="<?php echo htmlspecialchars($profile['first_name'] . ' ' . $profile['last_name']); ?>" class="profile-image">
                    <?php else: ?>
                        <div class="profile-image d-flex align-items-center justify-content-center bg-light">
                            <i class="fas fa-user fa-4x text-secondary"></i>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="col-md-6">
                    <h1 class="mb-2"><?php echo htmlspecialchars($profile['first_name'] . ' ' . $profile['last_name']); ?></h1>
                    
                    <?php if (!empty($profile['avg_rating'])): ?>
                        <div class="rating-stars mb-3">
                            <?php
                            $rating = round($profile['avg_rating']);
                            for ($i = 1; $i <= 5; $i++) {
                                if ($i <= $rating) {
                                    echo '<i class="fas fa-star"></i>';
                                } else {
                                    echo '<i class="far fa-star"></i>';
                                }
                            }
                            ?>
                            <span class="text-muted ms-2">(<?php echo $profile['rating_count']; ?> reviews)</span>
                        </div>
                    <?php endif; ?>
                    
                    <?php
                    $availabilityClass = '';
                    switch ($profile['availability']) {
                        case 'full_time':
                            $availabilityClass = 'bg-success';
                            break;
                        case 'part_time':
                            $availabilityClass = 'bg-info';
                            break;
                        case 'contract':
                            $availabilityClass = 'bg-warning';
                            break;
                        case 'freelance':
                            $availabilityClass = 'bg-danger';
                            break;
                    }
                    ?>
                    <span class="badge <?php echo $availabilityClass; ?> availability-badge mb-3">
                        Available for <?php echo ucwords(str_replace('_', ' ', $profile['availability'])); ?> work
                    </span>
                    
                    <p class="mb-2">
                        <i class="fas fa-church me-2 text-muted"></i> 
                        <?php echo !empty($profile['society_name']) ? htmlspecialchars($profile['society_name']) : 'Not specified'; ?>
                        <?php if (!empty($profile['circuit_name'])): ?>
                            <span class="text-muted"> | <?php echo htmlspecialchars($profile['circuit_name']); ?> Circuit</span>
                        <?php endif; ?>
                        <?php if (!empty($profile['diocese_name'])): ?>
                            <span class="text-muted"> | <?php echo htmlspecialchars($profile['diocese_name']); ?> Diocese</span>
                        <?php endif; ?>
                    </p>
                </div>
                <div class="col-md-3 text-md-end mt-3 mt-md-0">
                    <a href="mailto:<?php echo $profile['email']; ?>" class="btn btn-primary contact-btn mb-2">
                        <i class="fas fa-envelope me-2"></i> Contact
                    </a>
                    <?php if (!empty($profile['portfolio_url'])): ?>
                        <a href="<?php echo htmlspecialchars($profile['portfolio_url']); ?>" target="_blank" class="btn btn-outline-primary contact-btn d-block mt-2">
                            <i class="fas fa-globe me-2"></i> Portfolio
                        </a>
                    <?php endif; ?>
                    
                    <?php if (isLoggedIn() && !$isProfileOwner && $currentMemberId): ?>
                        <a href="rate-review.php?profile_id=<?php echo $profileId; ?>" class="btn btn-outline-warning contact-btn d-block mt-2">
                            <i class="fas fa-star me-2"></i> <?php echo $hasRated ? 'Update Review' : 'Rate & Review'; ?>
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Left Column - Skills and Experience -->
            <div class="col-lg-8">
                <!-- Skills Section -->
                <div class="card mb-4">
                    <div class="card-body">
                        <h3 class="section-title">Skills</h3>
                        <div>
                            <?php
                            if (!empty($profile['skills'])) {
                                $skills = explode(',', $profile['skills']);
                                foreach ($skills as $skill) {
                                    echo '<span class="skill-badge">' . htmlspecialchars(trim($skill)) . '</span> ';
                                }
                            } else {
                                echo '<p class="text-muted">No skills listed</p>';
                            }
                            ?>
                        </div>
                    </div>
                </div>

                <!-- Experience Section -->
                <div class="card mb-4">
                    <div class="card-body">
                        <h3 class="section-title">Experience</h3>
                        <?php if (!empty($profile['experience'])): ?>
                            <div><?php echo nl2br(htmlspecialchars($profile['experience'])); ?></div>
                        <?php else: ?>
                            <p class="text-muted">No experience information provided</p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Education Section -->
                <div class="card mb-4">
                    <div class="card-body">
                        <h3 class="section-title">Education</h3>
                        <?php if (!empty($profile['education'])): ?>
                            <div><?php echo nl2br(htmlspecialchars($profile['education'])); ?></div>
                        <?php else: ?>
                            <p class="text-muted">No education information provided</p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Completed Jobs Section -->
                <?php if (!empty($completedJobs)): ?>
                <div class="card mb-4">
                    <div class="card-body">
                        <h3 class="section-title">Completed Jobs</h3>
                        <div class="list-group">
                            <?php foreach ($completedJobs as $job): ?>
                                <a href="job-details.php?id=<?php echo $job['id']; ?>" class="list-group-item list-group-item-action">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h5 class="mb-1"><?php echo htmlspecialchars($job['title']); ?></h5>
                                        <small class="text-muted"><?php echo date('M Y', strtotime($job['created_at'])); ?></small>
                                    </div>
                                    <p class="mb-1"><?php echo htmlspecialchars(truncateText($job['description'], 100)); ?></p>
                                    <small class="text-muted"><?php echo htmlspecialchars($job['company_name']); ?></small>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Right Column - Reviews and Contact -->
            <div class="col-lg-4">
                <!-- Contact Information -->
                <div class="card mb-4">
                    <div class="card-body">
                        <h3 class="section-title">Contact Information</h3>
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="fas fa-envelope me-2 text-primary"></i> 
                                <a href="mailto:<?php echo $profile['email']; ?>"><?php echo htmlspecialchars($profile['email']); ?></a>
                            </li>
                            <?php if (!empty($profile['phone'])): ?>
                            <li class="mb-2">
                                <i class="fas fa-phone me-2 text-primary"></i> 
                                <a href="tel:<?php echo $profile['phone']; ?>"><?php echo htmlspecialchars($profile['phone']); ?></a>
                            </li>
                            <?php endif; ?>
                            <?php if (!empty($profile['portfolio_url'])): ?>
                            <li>
                                <i class="fas fa-globe me-2 text-primary"></i> 
                                <a href="<?php echo htmlspecialchars($profile['portfolio_url']); ?>" target="_blank">Portfolio Website</a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>

                <!-- Reviews Section -->
                <div class="card mb-4">
                    <div class="card-body">
                        <h3 class="section-title">Reviews</h3>
                        <?php if (empty($ratings)): ?>
                            <p class="text-muted">No reviews yet</p>
                        <?php else: ?>
                            <?php foreach ($ratings as $index => $rating): ?>
                                <?php if ($index < 3): // Show only 3 reviews initially ?>
                                    <div class="review-card p-3 mb-3">
                                        <div class="d-flex justify-content-between mb-2">
                                            <div>
                                                <strong><?php echo htmlspecialchars($rating['first_name'] . ' ' . $rating['last_name']); ?></strong>
                                                <?php if (!empty($rating['job_title'])): ?>
                                                    <small class="text-muted d-block">for <?php echo htmlspecialchars($rating['job_title']); ?></small>
                                                <?php endif; ?>
                                            </div>
                                            <div class="rating-stars">
                                                <?php
                                                for ($i = 1; $i <= 5; $i++) {
                                                    if ($i <= $rating['rating']) {
                                                        echo '<i class="fas fa-star"></i>';
                                                    } else {
                                                        echo '<i class="far fa-star"></i>';
                                                    }
                                                }
                                                ?>
                                            </div>
                                        </div>
                                        <p class="mb-1"><?php echo htmlspecialchars($rating['review']); ?></p>
                                        <small class="text-muted"><?php echo date('M d, Y', strtotime($rating['created_at'])); ?></small>
                                    </div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                            
                            <?php if (count($ratings) > 3): ?>
                                <div class="text-center mt-3">
                                    <button class="btn btn-outline-primary btn-sm" id="showMoreReviews">
                                        Show All Reviews (<?php echo count($ratings); ?>)
                                    </button>
                                </div>
                                
                                <div id="allReviews" style="display: none;">
                                    <?php foreach ($ratings as $index => $rating): ?>
                                        <?php if ($index >= 3): // Show remaining reviews when expanded ?>
                                            <div class="review-card p-3 mb-3">
                                                <div class="d-flex justify-content-between mb-2">
                                                    <div>
                                                        <strong><?php echo htmlspecialchars($rating['first_name'] . ' ' . $rating['last_name']); ?></strong>
                                                        <?php if (!empty($rating['job_title'])): ?>
                                                            <small class="text-muted d-block">for <?php echo htmlspecialchars($rating['job_title']); ?></small>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="rating-stars">
                                                        <?php
                                                        for ($i = 1; $i <= 5; $i++) {
                                                            if ($i <= $rating['rating']) {
                                                                echo '<i class="fas fa-star"></i>';
                                                            } else {
                                                                echo '<i class="far fa-star"></i>';
                                                            }
                                                        }
                                                        ?>
                                                    </div>
                                                </div>
                                                <p class="mb-1"><?php echo htmlspecialchars($rating['review']); ?></p>
                                                <small class="text-muted"><?php echo date('M d, Y', strtotime($rating['created_at'])); ?></small>
                                            </div>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Hire Me CTA -->
                <div class="card bg-primary text-white">
                    <div class="card-body text-center p-4">
                        <h4 class="mb-3">Need help with a project?</h4>
                        <p>Hire <?php echo htmlspecialchars($profile['first_name']); ?> for your next job opportunity.</p>
                        <a href="post-job.php" class="btn btn-light">Post a Job</a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Back to Showcase Button -->
        <div class="text-center mt-5">
            <a href="talent-showcase.php" class="btn btn-outline-primary">
                <i class="fas fa-arrow-left me-2"></i> Back to Talent Showcase
            </a>
        </div>
    </div>

    <!-- Footer -->
    <footer class="bg-dark text-white py-4 mt-5">
        <div class="container">
            <div class="row">
                <div class="col-md-4 mb-3">
                    <h5>GHAMECC Job Portal</h5>
                    <p>A platform for Ghana Methodist Church Choir members to find and post job opportunities.</p>
                </div>
                <div class="col-md-4 mb-3">
                    <h5>Quick Links</h5>
                    <ul class="list-unstyled">
                        <li><a href="index.php" class="text-white">Home</a></li>
                        <li><a href="post-job.php" class="text-white">Post a Job</a></li>
                        <li><a href="talent-showcase.php" class="text-white">Talent Showcase</a></li>
                        <li><a href="about.php" class="text-white">About</a></li>
                    </ul>
                </div>
                <div class="col-md-4 mb-3">
                    <h5>Contact</h5>
                    <address>
                        <p><i class="fas fa-envelope me-2"></i> info@ghamecc.org</p>
                        <p><i class="fas fa-phone me-2"></i> +233 XX XXX XXXX</p>
                    </address>
                </div>
            </div>
            <hr>
            <div class="text-center">
                <p>&copy; <?php echo date('Y'); ?> GHAMECC Job Portal. All rights reserved.</p>
            </div>
        </div>
    </footer>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Lightbox JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/js/lightbox.min.js"></script>
    <script>
        // Show more reviews functionality
        document.addEventListener('DOMContentLoaded', function() {
            const showMoreBtn = document.getElementById('showMoreReviews');
            const allReviews = document.getElementById('allReviews');
            
            if (showMoreBtn) {
                showMoreBtn.addEventListener('click', function() {
                    if (allReviews.style.display === 'none') {
                        allReviews.style.display = 'block';
                        showMoreBtn.textContent = 'Show Less';
                    } else {
                        allReviews.style.display = 'none';
                        showMoreBtn.textContent = 'Show All Reviews (<?php echo count($ratings); ?>)';
                    }
                });
            }
        });
    </script>
</body>
</html>
