<?php
/**
 * Job Portal - Rate and Review Page
 * GHAMECC Choir Management Platform
 * 
 * This page allows users to submit ratings and reviews for member profiles.
 */

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

// Check if user is logged in
if (!isLoggedIn()) {
    // Save the intended destination
    $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
    header('Location: ../login.php');
    exit;
}

// Get current user's member ID
$currentUserId = $_SESSION['user_id'];
$memberQuery = "SELECT id FROM members WHERE user_id = ?";
$currentMemberId = fetchValue($memberQuery, [$currentUserId]);

if (!$currentMemberId) {
    // User is not linked to a member record
    $_SESSION['error'] = "You must be registered as a member to submit ratings and reviews.";
    header('Location: talent-showcase.php');
    exit;
}

// Initialize variables
$errors = [];
$success = false;
$profileId = 0;
$memberId = 0;
$jobId = null;
$rating = 0;
$review = '';
$profile = null;
$jobs = [];

// Check if profile ID is provided
if (isset($_GET['profile_id']) && !empty($_GET['profile_id'])) {
    $profileId = (int)$_GET['profile_id'];
    
    // Get profile details
    $profileQuery = "SELECT mp.*, m.first_name, m.last_name, m.id as member_id, m.user_id as member_user_id
                    FROM member_profiles mp
                    JOIN members m ON mp.member_id = m.id
                    WHERE mp.id = ?";
    $profile = fetchRow($profileQuery, [$profileId]);
    
    if (!$profile) {
        $_SESSION['error'] = "Profile not found.";
        header('Location: talent-showcase.php');
        exit;
    }
    
    $memberId = $profile['member_id'];
    
    // Check if user is trying to rate themselves
    if ($memberId == $currentMemberId) {
        $_SESSION['error'] = "You cannot rate your own profile.";
        header('Location: profile-details.php?id=' . $profileId);
        exit;
    }
    
    // Get jobs that both the current user and the rated member have been involved with
    $jobsQuery = "SELECT j.id, j.title 
                 FROM jobs j
                 JOIN job_applications ja1 ON j.id = ja1.job_id AND ja1.member_id = ?
                 JOIN job_applications ja2 ON j.id = ja2.job_id AND ja2.member_id = ?
                 WHERE ja2.status = 'selected'
                 ORDER BY j.created_at DESC";
    $jobs = fetchRows($jobsQuery, [$currentMemberId, $memberId]);
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate input
    $profileId = isset($_POST['profile_id']) ? (int)$_POST['profile_id'] : 0;
    $memberId = isset($_POST['member_id']) ? (int)$_POST['member_id'] : 0;
    $jobId = !empty($_POST['job_id']) ? (int)$_POST['job_id'] : null;
    $rating = isset($_POST['rating']) ? (int)$_POST['rating'] : 0;
    $review = isset($_POST['review']) ? trim($_POST['review']) : '';
    
    // Get the user_id of the rated member for notifications
    $ratedUserQuery = "SELECT user_id FROM members WHERE id = ?";
    $ratedUserId = fetchValue($ratedUserQuery, [$memberId]);
    
    // Validate rating
    if ($rating < 1 || $rating > 5) {
        $errors[] = "Please select a rating between 1 and 5 stars.";
    }
    
    // Validate review
    if (empty($review)) {
        $errors[] = "Please provide a review.";
    } elseif (strlen($review) < 10) {
        $errors[] = "Review must be at least 10 characters long.";
    }
    
    // Check if user has already rated this member
    $existingRatingQuery = "SELECT id FROM member_ratings 
                           WHERE rater_id = ? AND rated_id = ?";
    $existingRatingParams = [$currentMemberId, $memberId];
    
    if ($jobId) {
        $existingRatingQuery .= " AND job_id = ?";
        $existingRatingParams[] = $jobId;
    }
    
    $existingRating = fetchValue($existingRatingQuery, $existingRatingParams);
    
    if ($existingRating) {
        // Update existing rating
        if (empty($errors)) {
            $updateQuery = "UPDATE member_ratings 
                           SET rating = ?, review = ?, updated_at = NOW() 
                           WHERE id = ?";
            $result = execute($updateQuery, [$rating, $review, $existingRating]);
            
            if ($result) {
                $success = true;
                $_SESSION['success'] = "Your rating and review have been updated.";
                
                // Send notification for updated rating/review
                if ($ratedUserId) {
                    createRatingNotification($ratedUserId, $currentUserId, $rating, $profileId);
                    createReviewNotification($ratedUserId, $currentUserId, $review, $profileId);
                }
                
                header('Location: profile-details.php?id=' . $profileId);
                exit;
            } else {
                $errors[] = "Failed to update your rating and review. Please try again.";
            }
        }
    } else {
        // Insert new rating
        if (empty($errors)) {
            $insertQuery = "INSERT INTO member_ratings 
                          (rater_id, rated_id, job_id, rating, review, created_at) 
                          VALUES (?, ?, ?, ?, ?, NOW())";
            $result = execute($insertQuery, [$currentMemberId, $memberId, $jobId, $rating, $review]);
            
            if ($result) {
                $success = true;
                $_SESSION['success'] = "Your rating and review have been submitted.";
                
                // Send notification to the rated member
                if ($ratedUserId) {
                    createRatingNotification($ratedUserId, $currentUserId, $rating, $profileId);
                    createReviewNotification($ratedUserId, $currentUserId, $review, $profileId);
                }
                
                header('Location: profile-details.php?id=' . $profileId);
                exit;
            } else {
                $errors[] = "Failed to submit your rating and review. Please try again.";
            }
        }
    }
}

// Page title
$pageTitle = "Rate and Review | 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">
    <style>
        .rating-container {
            display: flex;
            flex-direction: row-reverse;
            justify-content: center;
            align-items: center;
            margin: 30px 0;
        }
        .rating-container input {
            display: none;
        }
        .rating-container label {
            cursor: pointer;
            font-size: 2.5rem;
            color: #ddd;
            padding: 0 5px;
            transition: color 0.3s;
        }
        .rating-container label:hover,
        .rating-container label:hover ~ label,
        .rating-container input:checked ~ label {
            color: #ffc107;
        }
        .rating-text {
            text-align: center;
            margin-top: 10px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php include 'includes/job-portal-navbar.php'; ?>

    <!-- Main Content -->
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white">
                        <h2 class="mb-0">Rate and Review</h2>
                    </div>
                    <div class="card-body">
                        <?php if (!$profile): ?>
                            <div class="alert alert-danger">
                                Profile not found. Please select a valid profile to rate.
                            </div>
                            <div class="text-center mt-4">
                                <a href="talent-showcase.php" class="btn btn-primary">
                                    <i class="fas fa-arrow-left me-2"></i> Back to Talent Showcase
                                </a>
                            </div>
                        <?php else: ?>
                            <h4 class="mb-4">Rating for: <?php echo htmlspecialchars($profile['first_name'] . ' ' . $profile['last_name']); ?></h4>
                            
                            <?php if (!empty($errors)): ?>
                                <div class="alert alert-danger">
                                    <ul class="mb-0">
                                        <?php foreach ($errors as $error): ?>
                                            <li><?php echo $error; ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            <?php endif; ?>
                            
                            <form action="rate-review.php" method="post">
                                <input type="hidden" name="profile_id" value="<?php echo $profileId; ?>">
                                <input type="hidden" name="member_id" value="<?php echo $memberId; ?>">
                                
                                <!-- Rating Stars -->
                                <div class="form-group mb-4">
                                    <label class="form-label">Your Rating:</label>
                                    <div class="rating-container">
                                        <input type="radio" id="star5" name="rating" value="5" <?php echo (isset($rating) && $rating == 5) ? 'checked' : ''; ?>>
                                        <label for="star5" title="5 stars"><i class="fas fa-star"></i></label>
                                        
                                        <input type="radio" id="star4" name="rating" value="4" <?php echo (isset($rating) && $rating == 4) ? 'checked' : ''; ?>>
                                        <label for="star4" title="4 stars"><i class="fas fa-star"></i></label>
                                        
                                        <input type="radio" id="star3" name="rating" value="3" <?php echo (isset($rating) && $rating == 3) ? 'checked' : ''; ?>>
                                        <label for="star3" title="3 stars"><i class="fas fa-star"></i></label>
                                        
                                        <input type="radio" id="star2" name="rating" value="2" <?php echo (isset($rating) && $rating == 2) ? 'checked' : ''; ?>>
                                        <label for="star2" title="2 stars"><i class="fas fa-star"></i></label>
                                        
                                        <input type="radio" id="star1" name="rating" value="1" <?php echo (isset($rating) && $rating == 1) ? 'checked' : ''; ?>>
                                        <label for="star1" title="1 star"><i class="fas fa-star"></i></label>
                                    </div>
                                    <div class="rating-text" id="ratingText">Select a rating</div>
                                </div>
                                
                                <!-- Job Selection (if applicable) -->
                                <?php if (!empty($jobs)): ?>
                                <div class="form-group mb-4">
                                    <label for="job_id" class="form-label">Related Job (Optional):</label>
                                    <select class="form-select" id="job_id" name="job_id">
                                        <option value="">-- Select a job (optional) --</option>
                                        <?php foreach ($jobs as $job): ?>
                                            <option value="<?php echo $job['id']; ?>" <?php echo (isset($jobId) && $jobId == $job['id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($job['title']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="form-text">If your review is related to a specific job, please select it.</div>
                                </div>
                                <?php endif; ?>
                                
                                <!-- Review Text -->
                                <div class="form-group mb-4">
                                    <label for="review" class="form-label">Your Review:</label>
                                    <textarea class="form-control" id="review" name="review" rows="5" required><?php echo htmlspecialchars($review); ?></textarea>
                                    <div class="form-text">Please provide honest and constructive feedback about your experience.</div>
                                </div>
                                
                                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                    <a href="profile-details.php?id=<?php echo $profileId; ?>" class="btn btn-outline-secondary me-md-2">
                                        <i class="fas fa-times me-2"></i> Cancel
                                    </a>
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-paper-plane me-2"></i> Submit Review
                                    </button>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </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>
    <script>
        // Update rating text based on selection
        document.addEventListener('DOMContentLoaded', function() {
            const ratingInputs = document.querySelectorAll('input[name="rating"]');
            const ratingText = document.getElementById('ratingText');
            const ratingDescriptions = {
                1: 'Poor',
                2: 'Fair',
                3: 'Good',
                4: 'Very Good',
                5: 'Excellent'
            };
            
            // Set initial text if a rating is already selected
            ratingInputs.forEach(input => {
                if (input.checked) {
                    ratingText.textContent = ratingDescriptions[input.value];
                }
            });
            
            // Update text when rating changes
            ratingInputs.forEach(input => {
                input.addEventListener('change', function() {
                    ratingText.textContent = ratingDescriptions[this.value];
                });
            });
        });
    </script>
</body>
</html>
