<?php
require_once '../includes/User.php';
require_once '../includes/db_config.php';

if (!User::isLoggedIn()) {
    header("Location: ../login.php");
    exit();
}

$me = User::getCurrentUser();
$order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;

if (!$order_id) {
    header("Location: profile.php");
    exit();
}

try {
    $db = getDBConnection();
    
    $order_stmt = $db->prepare("
        SELECT o.*, GROUP_CONCAT(s.name SEPARATOR ', ') as services
        FROM orders o
        LEFT JOIN order_items oi ON o.id = oi.order_id
        LEFT JOIN services s ON oi.service_id = s.id
        WHERE o.id = ? AND o.user_id = ? AND o.status = 'delivered'
        GROUP BY o.id
    ");
    $order_stmt->execute([$order_id, $me['id']]);
    $order = $order_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        header("Location: /allura/php/profile.php");
        exit();
    }
    
    $review_check = $db->prepare("SELECT id FROM reviews WHERE order_id = ? AND user_id = ?");
    $review_check->execute([$order_id, $me['id']]);
    $existing_review = $review_check->fetch();
    
    if ($existing_review) {
        $review_exists = true;
    } else {
        $review_exists = false;
    }
    
} catch (PDOException $e) {
    error_log("Review page error: " . $e->getMessage());
    header("Location: profile.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$review_exists) {
    $service_rating = (int)$_POST['service_rating'];
    $delivery_rating = (int)$_POST['delivery_rating'];
    $comment = trim($_POST['comment']);
    
    if ($service_rating >= 1 && $service_rating <= 5 && $delivery_rating >= 1 && $delivery_rating <= 5) {
        try {
            $insert_review = $db->prepare("
                INSERT INTO reviews (user_id, order_id, service_rating, delivery_rating, comment, created_at)
                VALUES (?, ?, ?, ?, ?, NOW())
            ");
            $insert_review->execute([$me['id'], $order_id, $service_rating, $delivery_rating, $comment]);
            
            $_SESSION['review_success'] = true;
            header("Location: /allura/php/profile.php");
            exit();
            
        } catch (PDOException $e) {
            $error = "Error submitting review. Please try again.";
            error_log("Review submission error: " . $e->getMessage());
            
            if (strpos($e->getMessage(), 'Unknown column') !== false) {
                $error = "Database structure error. Please contact administrator.";
            }
        }
    } else {
        $error = "Please provide valid ratings (1-5 stars).";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rate Your Experience - Allura Dry Clean</title>
    <?php include '../includes/header.php'; ?>
    <link rel="stylesheet" href="/allura/css/style.css">
</head>
<body>
    <div class="review-container">
        <div class="review-card">
            <?php if ($review_exists): ?>
                <div class="already-reviewed">
                    <h3>✓ Review Already Submitted</h3>
                    <p>Thank you! You have already reviewed this order.</p>
                    <a href="/allura/php/profile.php" class="btn btn-primary">Back to Profile</a>
                </div>
            <?php else: ?>
                <h2 style="text-align: center; color: #333; margin-bottom: 2rem;">Rate Your Experience</h2>
                
                <div class="order-info">
                    <div class="order-title">Order #<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></div>
                    <div class="order-details">
                        <strong>Services:</strong> <?php echo htmlspecialchars($order['services']); ?><br>
                        <strong>Total:</strong> SAR <?php echo number_format($order['total_amount'], 2); ?><br>
                        <strong>Delivered:</strong> <?php echo date('F j, Y', strtotime($order['delivery_date'])); ?>
                    </div>
                </div>
                
                <?php if (isset($error)): ?>
                    <div class="error-message"><?php echo htmlspecialchars($error); ?></div>
                <?php endif; ?>
                
                <form method="POST" id="reviewForm">
                    <div class="rating-section">
                        <div class="rating-title">How would you rate our service quality?</div>
                        <div class="star-rating" data-rating="service_rating">
                            <span class="star" data-value="1">★</span>
                            <span class="star" data-value="2">★</span>
                            <span class="star" data-value="3">★</span>
                            <span class="star" data-value="4">★</span>
                            <span class="star" data-value="5">★</span>
                        </div>
                        <input type="hidden" name="service_rating" id="service_rating" required>
                    </div>
                    
                    <div class="rating-section">
                        <div class="rating-title">How would you rate our delivery service?</div>
                        <div class="star-rating" data-rating="delivery_rating">
                            <span class="star" data-value="1">★</span>
                            <span class="star" data-value="2">★</span>
                            <span class="star" data-value="3">★</span>
                            <span class="star" data-value="4">★</span>
                            <span class="star" data-value="5">★</span>
                        </div>
                        <input type="hidden" name="delivery_rating" id="delivery_rating" required>
                    </div>
                    
                    <div class="comment-section">
                        <label for="comment">Additional Comments (Optional)</label>
                        <textarea name="comment" id="comment" placeholder="Tell us about your experience..."></textarea>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">Submit Review</button>
                        <a href="/allura/php/profile.php" class="btn btn-secondary">Cancel</a>
                </form>
            <?php endif; ?>
        </div>
    </div>
    
    <script src="../js/review.js"></script>
    
    <?php include '../includes/footer.php'; ?>
</body>
</html>
