<?php
// CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once __DIR__ . '/db.php';

// Ensure product_reviews table exists with status column (MySQL compatible)
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS product_reviews (
        id VARCHAR(50) PRIMARY KEY,
        product_id VARCHAR(50) NOT NULL,
        order_id VARCHAR(50) NOT NULL,
        user_email VARCHAR(100) NOT NULL,
        user_name VARCHAR(100) NOT NULL,
        rating INT DEFAULT 5,
        title VARCHAR(150),
        comment TEXT,
        video_url TEXT,
        status VARCHAR(20) DEFAULT 'pending',
        created_at BIGINT
    )");
    
    $stmt = $pdo->query("SHOW COLUMNS FROM product_reviews LIKE 'status'");
    $cols = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
    if (empty($cols)) {
        $pdo->exec("ALTER TABLE product_reviews ADD COLUMN status VARCHAR(20) DEFAULT 'pending'");
    }
} catch (Exception $e) {
    try {
        $pdo->exec("ALTER TABLE product_reviews ADD COLUMN status VARCHAR(20) DEFAULT 'pending'");
    } catch (Exception $e2) {
        // Continue if column already exists
    }
}

$action = $_GET['action'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if ($action === 'admin_list') {
        // Fetch all reviews for admin moderation
        $stmt = $pdo->query("SELECT pr.*, p.name as product_name, p.vendorEmail 
                             FROM product_reviews pr 
                             LEFT JOIN products p ON pr.product_id = p.id 
                             ORDER BY pr.created_at DESC");
        $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($reviews);
        exit;
    }

    $productId = $_GET['product_id'] ?? '';
    if ($productId) {
        // Public endpoint: ONLY return approved reviews for product
        $stmt = $pdo->prepare("SELECT * FROM product_reviews WHERE product_id = ? AND status = 'approved' ORDER BY created_at DESC");
        $stmt->execute([$productId]);
        $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($reviews);
    } else {
        $stmt = $pdo->query("SELECT * FROM product_reviews WHERE status = 'approved' ORDER BY created_at DESC");
        $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($reviews);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    
    if ($action === 'approve') {
        $id = $data['id'] ?? '';
        if (!$id) {
            http_response_code(400);
            echo json_encode(["error" => "Review ID required"]);
            exit;
        }
        $stmt = $pdo->prepare("UPDATE product_reviews SET status = 'approved' WHERE id = ?");
        $success = $stmt->execute([$id]);
        echo json_encode(["success" => $success, "id" => $id, "status" => "approved"]);
        exit;
    }

    if ($action === 'reject') {
        $id = $data['id'] ?? '';
        if (!$id) {
            http_response_code(400);
            echo json_encode(["error" => "Review ID required"]);
            exit;
        }
        $stmt = $pdo->prepare("UPDATE product_reviews SET status = 'rejected' WHERE id = ?");
        $success = $stmt->execute([$id]);
        echo json_encode(["success" => $success, "id" => $id, "status" => "rejected"]);
        exit;
    }

    if ($action === 'delete') {
        $id = $data['id'] ?? '';
        if (!$id) {
            http_response_code(400);
            echo json_encode(["error" => "Review ID required"]);
            exit;
        }
        $stmt = $pdo->prepare("DELETE FROM product_reviews WHERE id = ?");
        $success = $stmt->execute([$id]);
        echo json_encode(["success" => $success, "id" => $id]);
        exit;
    }

    if (!$data || !isset($data['product_id']) || !isset($data['order_id'])) {
        http_response_code(400);
        echo json_encode(["error" => "Invalid payload"]);
        exit;
    }

    $id = 'rev_' . time() . '_' . rand(100, 999);
    $productId = $data['product_id'];
    $orderId = $data['order_id'];
    $userEmail = $data['user_email'] ?? 'customer@example.com';
    $userName = $data['user_name'] ?? 'Verified Buyer';
    $rating = (int)($data['rating'] ?? 5);
    $title = $data['title'] ?? 'Great Product!';
    $comment = $data['comment'] ?? '';
    $videoUrl = $data['video_url'] ?? '';
    $status = 'pending'; // New reviews require admin confirmation before appearing
    $createdAt = time() * 1000;

    $stmt = $pdo->prepare("INSERT INTO product_reviews (id, product_id, order_id, user_email, user_name, rating, title, comment, video_url, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $success = $stmt->execute([$id, $productId, $orderId, $userEmail, $userName, $rating, $title, $comment, $videoUrl, $status, $createdAt]);

    echo json_encode([
        "success" => $success,
        "review" => [
            "id" => $id,
            "product_id" => $productId,
            "order_id" => $orderId,
            "user_email" => $userEmail,
            "user_name" => $userName,
            "rating" => $rating,
            "title" => $title,
            "comment" => $comment,
            "video_url" => $videoUrl,
            "status" => $status,
            "created_at" => $createdAt
        ]
    ]);
    exit;
}
?>
