<?php
/**
 * Reviews API Endpoint
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Auth.php';

header('Content-Type: application/json');

$auth = new Auth();
$db = Database::getInstance();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

$userId = $auth->getUserId();

try {
    switch ($method) {
        case 'GET':
            $productId = $_GET['product_id'] ?? 0;
            
            if ($productId) {
                // Get reviews for product
                $reviews = $db->fetchAll(
                    "SELECT r.*, u.first_name, u.last_name
                     FROM reviews r
                     INNER JOIN users u ON r.user_id = u.id
                     WHERE r.product_id = ? AND r.is_approved = 1
                     ORDER BY r.created_at DESC",
                    [$productId]
                );
                
                // Calculate average rating
                $avgRating = $db->fetchOne(
                    "SELECT AVG(rating) as avg_rating, COUNT(*) as total
                     FROM reviews WHERE product_id = ? AND is_approved = 1",
                    [$productId]
                );
                
                echo json_encode([
                    'success' => true,
                    'reviews' => $reviews,
                    'average_rating' => round($avgRating['avg_rating'] ?? 0, 1),
                    'total_reviews' => $avgRating['total'] ?? 0
                ]);
            }
            break;

        case 'POST':
            if (!$userId) {
                http_response_code(401);
                echo json_encode(['success' => false, 'message' => 'Login required']);
                exit;
            }
            
            $data = json_decode(file_get_contents('php://input'), true);
            
            if ($action === 'create') {
                $productId = $data['product_id'] ?? 0;
                $orderId = $data['order_id'] ?? null;
                
                // Check if user already reviewed this product
                $existing = $db->fetchOne(
                    "SELECT id FROM reviews WHERE user_id = ? AND product_id = ?",
                    [$userId, $productId]
                );
                
                if ($existing) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'You have already reviewed this product']);
                } else {
                    $db->execute(
                        "INSERT INTO reviews (user_id, product_id, order_id, rating, title, comment, is_approved)
                         VALUES (?, ?, ?, ?, ?, ?, 0)",
                        [
                            $userId,
                            $productId,
                            $orderId,
                            $data['rating'],
                            $data['title'] ?? null,
                            $data['comment'] ?? null
                        ]
                    );
                    echo json_encode(['success' => true]);
                }
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

