<?php
// submit-review.php - Handle Review Submission
ob_start();
require_once 'includes/config.php';

// Check if user is logged in
if(!isLoggedIn()) {
    $_SESSION['error'] = 'রিভিউ দিতে লগইন করতে হবে';
    header('Location: auth.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$course_id = $_POST['course_id'] ?? $_GET['course_id'] ?? 0;
$rating = $_POST['rating'] ?? 0;
$comment = trim($_POST['comment'] ?? '');

// Validate
if(empty($course_id) || empty($rating) || empty($comment)) {
    $_SESSION['error'] = 'অনুগ্রহ করে রেটিং এবং মতামত দিন';
    header('Location: course-details.php?id=' . $course_id);
    exit;
}

// Validate rating
if($rating < 1 || $rating > 5) {
    $_SESSION['error'] = 'রেটিং ১ থেকে ৫ এর মধ্যে হতে হবে';
    header('Location: course-details.php?id=' . $course_id);
    exit;
}

// Check if user is enrolled in this course
$stmt = $pdo->prepare("
    SELECT COUNT(*) as enrolled 
    FROM enrollments 
    WHERE user_id = ? AND course_id = ? AND payment_status = 'completed'
    AND (expires_at IS NULL OR expires_at >= CURDATE())
");
$stmt->execute([$user_id, $course_id]);
$enrollment = $stmt->fetch();

if($enrollment['enrolled'] == 0) {
    $_SESSION['error'] = 'শুধুমাত্র এনরোল করা শিক্ষার্থীরা রিভিউ দিতে পারবেন';
    header('Location: course-details.php?id=' . $course_id);
    exit;
}

// Check if user already reviewed this course
$stmt = $pdo->prepare("SELECT id FROM reviews WHERE user_id = ? AND course_id = ?");
$stmt->execute([$user_id, $course_id]);
if($stmt->fetch()) {
    $_SESSION['error'] = 'আপনি ইতিমধ্যে এই কোর্সে রিভিউ দিয়েছেন';
    header('Location: course-details.php?id=' . $course_id);
    exit;
}

// Insert review
try {
    $stmt = $pdo->prepare("
        INSERT INTO reviews (user_id, course_id, rating, comment, created_at) 
        VALUES (?, ?, ?, ?, NOW())
    ");
    $stmt->execute([$user_id, $course_id, $rating, $comment]);
    
    $_SESSION['success'] = 'আপনার রিভিউ সফলভাবে জমা হয়েছে! ধন্যবাদ!';
    
} catch(PDOException $e) {
    $_SESSION['error'] = 'রিভিউ জমা দিতে সমস্যা হয়েছে। আবার চেষ্টা করুন।';
    error_log("Review Error: " . $e->getMessage());
}

// Redirect back to course page
header('Location: course-details.php?id=' . $course_id);
exit;
ob_end_flush();
?>