<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../includes/functions.php';

header('Content-Type: application/json');
$db = getDB();

$method = $_SERVER['REQUEST_METHOD'];
$userId = $_SESSION['user_id'] ?? null;

if (!$userId) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Authentication required']);
    exit;
}

switch ($method) {
    case 'GET':
        handleGetReviews($db, $userId);
        break;
    case 'POST':
        handleSubmitReview($db, $userId);
        break;
    case 'PUT':
        handleUpdateReview($db, $userId);
        break;
    case 'DELETE':
        handleDeleteReview($db, $userId);
        break;
    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
        break;
}

function handleGetReviews($db, $userId) {
    $type = $_GET['type'] ?? 'course'; // 'course' or 'exam'
    $itemId = intval($_GET['item_id'] ?? 0);
    $limit = intval($_GET['limit'] ?? 10);
    $offset = intval($_GET['offset'] ?? 0);

    if (!$itemId) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Item ID required']);
        return;
    }

    try {
        $table = $type === 'exam' ? 'exam_reviews' : 'course_reviews';
        $idField = $type === 'exam' ? 'exam_id' : 'course_id';

        // Get reviews
        $stmt = $db->prepare("
            SELECT r.*, u.username, up.first_name, up.last_name, up.avatar
            FROM {$table} r
            JOIN users u ON r.student_id = u.id
            LEFT JOIN user_profiles up ON u.id = up.user_id
            WHERE r.{$idField} = ? AND r.status = 'approved'
            ORDER BY r.created_at DESC
            LIMIT ? OFFSET ?
        ");
        $stmt->execute([$itemId, $limit, $offset]);
        $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Get average rating and count
        $stmt = $db->prepare("
            SELECT AVG(rating) as avg_rating, COUNT(*) as total_reviews
            FROM {$table}
            WHERE {$idField} = ? AND status = 'approved'
        ");
        $stmt->execute([$itemId]);
        $stats = $stmt->fetch(PDO::FETCH_ASSOC);

        // Check if user has already reviewed
        $stmt = $db->prepare("
            SELECT id, rating, review_title, review_text
            FROM {$table}
            WHERE {$idField} = ? AND student_id = ?
        ");
        $stmt->execute([$itemId, $userId]);
        $userReview = $stmt->fetch(PDO::FETCH_ASSOC);

        echo json_encode([
            'success' => true,
            'reviews' => $reviews,
            'stats' => $stats,
            'user_review' => $userReview
        ]);

    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
    }
}

function handleSubmitReview($db, $userId) {
    $input = json_decode(file_get_contents('php://input'), true);

    $type = $input['type'] ?? 'course'; // 'course' or 'exam'
    $itemId = intval($input['item_id'] ?? 0);
    $rating = intval($input['rating'] ?? 0);
    $reviewTitle = trim($input['review_title'] ?? '');
    $reviewText = trim($input['review_text'] ?? '');

    if (!$itemId || $rating < 1 || $rating > 5) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Invalid input data']);
        return;
    }

    try {
        $table = $type === 'exam' ? 'exam_reviews' : 'course_reviews';
        $idField = $type === 'exam' ? 'exam_id' : 'course_id';

        // Check if user has permission (completed the course/exam)
        $completedCheck = $type === 'exam' ?
            "SELECT 1 FROM exam_attempts WHERE exam_id = ? AND student_id = ? AND is_passed = 1" :
            "SELECT 1 FROM course_enrollments WHERE course_id = ? AND student_id = ? AND status = 'completed'";

        $stmt = $db->prepare($completedCheck);
        $stmt->execute([$itemId, $userId]);
        $isCompleted = $stmt->fetch(PDO::FETCH_ASSOC);

        // Insert or update review
        $stmt = $db->prepare("
            INSERT INTO {$table} ({$idField}, student_id, rating, review_title, review_text, is_verified, status)
            VALUES (?, ?, ?, ?, ?, ?, 'approved')
            ON DUPLICATE KEY UPDATE
                rating = VALUES(rating),
                review_title = VALUES(review_title),
                review_text = VALUES(review_text),
                is_verified = VALUES(is_verified),
                status = 'approved',
                updated_at = CURRENT_TIMESTAMP
        ");

        $stmt->execute([
            $itemId,
            $userId,
            $rating,
            $reviewTitle,
            $reviewText,
            $isCompleted ? 1 : 0
        ]);

        echo json_encode([
            'success' => true,
            'message' => 'Review submitted successfully and is now live!',
            'is_verified' => $isCompleted ? true : false
        ]);

    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
    }
}

function handleUpdateReview($db, $userId) {
    $input = json_decode(file_get_contents('php://input'), true);

    $type = $input['type'] ?? 'course';
    $itemId = intval($input['item_id'] ?? 0);
    $rating = intval($input['rating'] ?? 0);
    $reviewTitle = trim($input['review_title'] ?? '');
    $reviewText = trim($input['review_text'] ?? '');

    if (!$itemId || $rating < 1 || $rating > 5) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Invalid input data']);
        return;
    }

    try {
        $table = $type === 'exam' ? 'exam_reviews' : 'course_reviews';
        $idField = $type === 'exam' ? 'exam_id' : 'course_id';

        $stmt = $db->prepare("
            UPDATE {$table}
            SET rating = ?, review_title = ?, review_text = ?, updated_at = CURRENT_TIMESTAMP
            WHERE {$idField} = ? AND student_id = ?
        ");

        $stmt->execute([$rating, $reviewTitle, $reviewText, $itemId, $userId]);

        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Review updated successfully']);
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'error' => 'Review not found']);
        }

    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
    }
}

function handleDeleteReview($db, $userId) {
    $type = $_GET['type'] ?? 'course';
    $itemId = intval($_GET['item_id'] ?? 0);

    if (!$itemId) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Item ID required']);
        return;
    }

    try {
        $table = $type === 'exam' ? 'exam_reviews' : 'course_reviews';
        $idField = $type === 'exam' ? 'exam_id' : 'course_id';

        $stmt = $db->prepare("DELETE FROM {$table} WHERE {$idField} = ? AND student_id = ?");
        $stmt->execute([$itemId, $userId]);

        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Review deleted successfully']);
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'error' => 'Review not found']);
        }

    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
    }
}
?>