<?php
require_once __DIR__ . '/../functions.php';
requireAdmin();
$page_title = 'Reviews';
$db = db();

if (isset($_GET['approve'])) {
    $db->prepare("UPDATE reviews SET is_approved = 1 WHERE id = ?")->execute([(int)$_GET['approve']]);
    flash('success', 'Review approved!');
    header('Location: reviews.php');
    exit;
}
if (isset($_GET['delete'])) {
    $db->prepare("DELETE FROM reviews WHERE id = ?")->execute([(int)$_GET['delete']]);
    flash('success', 'Review deleted!');
    header('Location: reviews.php');
    exit;
}

$reviews = $db->query("SELECT r.*, u.name as user_name, p.name as product_name FROM reviews r JOIN users u ON r.user_id = u.id JOIN products p ON r.product_id = p.id ORDER BY r.created_at DESC")->fetchAll();

require_once __DIR__ . '/../includes/admin-header.php';
?>
<div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
    <table class="w-full text-sm">
        <thead><tr class="text-left bg-gray-50 text-gray-500"><th class="px-4 py-3 font-medium">Product</th><th class="px-4 py-3 font-medium">User</th><th class="px-4 py-3 font-medium">Rating</th><th class="px-4 py-3 font-medium">Review</th><th class="px-4 py-3 font-medium">Status</th><th class="px-4 py-3 font-medium">Date</th><th class="px-4 py-3 font-medium"></th></tr></thead>
        <tbody>
            <?php foreach ($reviews as $r): ?>
            <tr class="border-t">
                <td class="px-4 py-3 font-medium text-gray-800"><?= h($r['product_name']) ?></td>
                <td class="px-4 py-3 text-gray-500"><?= h($r['user_name']) ?></td>
                <td class="px-4 py-3"><?php for ($i=1;$i<=5;$i++): ?><i class="fas fa-star text-xs <?= $i <= $r['rating'] ? 'text-yellow-400' : 'text-gray-200' ?>"></i><?php endfor; ?></td>
                <td class="px-4 py-3 max-w-xs truncate"><?= h($r['title'] ?: $r['comment']) ?></td>
                <td class="px-4 py-3"><?= $r['is_approved'] ? '<span class="text-green-600 text-xs font-medium">Approved</span>' : '<span class="text-yellow-600 text-xs font-medium">Pending</span>' ?></td>
                <td class="px-4 py-3 text-gray-500 text-xs"><?= date('d M Y', strtotime($r['created_at'])) ?></td>
                <td class="px-4 py-3">
                    <?php if (!$r['is_approved']): ?><a href="reviews.php?approve=<?= $r['id'] ?>" class="text-green-600 hover:underline text-xs mr-2">Approve</a><?php endif; ?>
                    <a href="reviews.php?delete=<?= $r['id'] ?>" class="text-red-500 hover:underline text-xs" onclick="return confirm('Delete?')">Delete</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>
