<?php
/**
 * Página de Avaliações - MontaLoja SaaS
 * Gerenciamento de avaliações de produtos
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/check-access.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Processar ações POST
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $reviewId = intval($_POST['review_id'] ?? 0);

    try {
        if ($action === 'approve' && $reviewId) {
            $stmt = $pdo->prepare("UPDATE product_reviews SET is_approved = 1, updated_at = NOW() WHERE id = ? AND store_id = ?");
            $stmt->execute([$reviewId, $storeId]);
            $message = 'Avaliação aprovada com sucesso!';
            $messageType = 'success';
        } elseif ($action === 'reject' && $reviewId) {
            $stmt = $pdo->prepare("UPDATE product_reviews SET is_approved = 0, updated_at = NOW() WHERE id = ? AND store_id = ?");
            $stmt->execute([$reviewId, $storeId]);
            $message = 'Avaliação rejeitada.';
            $messageType = 'warning';
        } elseif ($action === 'delete' && $reviewId) {
            // Buscar fotos para deletar
            $photoStmt = $pdo->prepare("SELECT photos FROM product_reviews WHERE id = ? AND store_id = ?");
            $photoStmt->execute([$reviewId, $storeId]);
            $photoRow = $photoStmt->fetch(PDO::FETCH_ASSOC);
            if ($photoRow && !empty($photoRow['photos'])) {
                $photos = json_decode($photoRow['photos'], true);
                if (is_array($photos)) {
                    foreach ($photos as $photo) {
                        $filePath = __DIR__ . '/../' . ltrim($photo, '/');
                        if (file_exists($filePath)) @unlink($filePath);
                    }
                }
            }
            $stmt = $pdo->prepare("DELETE FROM product_reviews WHERE id = ? AND store_id = ?");
            $stmt->execute([$reviewId, $storeId]);
            $message = 'Avaliação excluída com sucesso!';
            $messageType = 'success';
        }
    } catch (Exception $e) {
        $message = 'Erro ao processar: ' . $e->getMessage();
        $messageType = 'error';
    }

    // Redirect PRG
    if ($message) {
        $_SESSION['flash_message'] = $message;
        $_SESSION['flash_type'] = $messageType;
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
}

// Flash messages
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $messageType = $_SESSION['flash_type'] ?? 'success';
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
}

// Filtros
$statusFilter = $_GET['status'] ?? '';
$ratingFilter = intval($_GET['rating'] ?? 0);
$searchFilter = trim($_GET['search'] ?? '');
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Build query
$where = ['r.store_id = ?'];
$params = [$storeId];

if ($statusFilter === 'approved') {
    $where[] = 'r.is_approved = 1';
} elseif ($statusFilter === 'pending') {
    $where[] = 'r.is_approved = 0';
}

if ($ratingFilter >= 1 && $ratingFilter <= 5) {
    $where[] = 'r.rating = ?';
    $params[] = $ratingFilter;
}

if ($searchFilter) {
    $where[] = '(r.author_name LIKE ? OR r.comment LIKE ? OR p.name LIKE ?)';
    $s = "%$searchFilter%";
    $params[] = $s;
    $params[] = $s;
    $params[] = $s;
}

$whereClause = implode(' AND ', $where);

// Stats
try {
    $statsStmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total,
            SUM(CASE WHEN is_approved = 1 THEN 1 ELSE 0 END) as approved,
            SUM(CASE WHEN is_approved = 0 THEN 1 ELSE 0 END) as pending,
            COALESCE(AVG(rating), 0) as avg_rating
        FROM product_reviews WHERE store_id = ?
    ");
    $statsStmt->execute([$storeId]);
    $stats = $statsStmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $stats = ['total' => 0, 'approved' => 0, 'pending' => 0, 'avg_rating' => 0];
}

// Rating distribution
try {
    $distStmt = $pdo->prepare("SELECT rating, COUNT(*) as cnt FROM product_reviews WHERE store_id = ? GROUP BY rating ORDER BY rating DESC");
    $distStmt->execute([$storeId]);
    $ratingDist = [];
    while ($row = $distStmt->fetch(PDO::FETCH_ASSOC)) {
        $ratingDist[$row['rating']] = $row['cnt'];
    }
} catch (Exception $e) {
    $ratingDist = [];
}

// Total count
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM product_reviews r LEFT JOIN products p ON r.product_id = p.id WHERE $whereClause");
$countStmt->execute($params);
$total = $countStmt->fetchColumn();
$totalPages = max(1, ceil($total / $perPage));

// Fetch reviews
$sql = "SELECT r.*, p.name as product_name, p.image_url as product_image
        FROM product_reviews r
        LEFT JOIN products p ON r.product_id = p.id
        WHERE $whereClause
        ORDER BY r.created_at DESC
        LIMIT $perPage OFFSET $offset";
$reviewsStmt = $pdo->prepare($sql);
$reviewsStmt->execute($params);
$reviews = $reviewsStmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Avaliações';
include __DIR__ . '/../includes/dashboard-header.php';
?>

<?php include __DIR__ . '/../includes/responsive-styles.php'; ?>

<style>
/* Stars */
.stars { display: inline-flex; gap: 2px; }
.stars iconify-icon { font-size: 1rem; }
.stars .filled { color: #fbbf24; }
.stars .empty { color: var(--border); }

/* Big Rating */
.big-rating { text-align: center; }
.big-rating-number { font-size: 3rem; font-weight: 800; color: var(--primary); line-height: 1; }
.big-rating .stars iconify-icon { font-size: 1.5rem; }
.big-rating-count { font-size: 0.85rem; color: var(--text-muted); margin-top: 4px; }

/* Distribution */
.rating-bars { display: flex; flex-direction: column; gap: 6px; }
.rating-bar-row { display: flex; align-items: center; gap: 8px; font-size: 0.85rem; }
.rating-bar-label { width: 55px; color: var(--text-muted); white-space: nowrap; display: flex; align-items: center; gap: 4px; }
.rating-bar-track { flex: 1; height: 8px; background: var(--border); border-radius: 4px; overflow: hidden; }
.rating-bar-fill { height: 100%; background: #fbbf24; border-radius: 4px; transition: width 0.5s ease; }
.rating-bar-count { width: 30px; text-align: right; font-size: 0.8rem; color: var(--text-muted); font-weight: 600; }

/* Review Card */
.review-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius-lg); padding: 1.25rem; margin-bottom: 1rem; transition: all 0.2s; }
.review-card:hover { border-color: var(--primary); }
.review-card-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 1rem; margin-bottom: 1rem; flex-wrap: wrap; }
.review-author-info { display: flex; align-items: center; gap: 0.75rem; }
.review-avatar { width: 44px; height: 44px; border-radius: 50%; background: var(--primary); color: #000; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 1.1rem; flex-shrink: 0; }
.review-author-name { font-weight: 600; font-size: 0.95rem; }
.review-author-email { font-size: 0.8rem; color: var(--text-muted); }
.review-meta { display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap; }
.review-date { font-size: 0.8rem; color: var(--text-muted); }
.review-product { display: flex; align-items: center; gap: 0.75rem; padding: 0.75rem; background: var(--bg-dark); border-radius: var(--radius-md); margin-bottom: 1rem; }
.review-product-img { width: 48px; height: 48px; border-radius: 8px; object-fit: cover; border: 1px solid var(--border); background: var(--bg-card); }
.review-product-name { font-weight: 600; font-size: 0.9rem; }
.review-comment { font-size: 0.95rem; color: var(--text-secondary); line-height: 1.6; margin-bottom: 1rem; }
.review-photos { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 1rem; }
.review-photo { width: 80px; height: 80px; border-radius: 8px; object-fit: cover; border: 1px solid var(--border); cursor: pointer; transition: transform 0.2s; }
.review-photo:hover { transform: scale(1.05); }
.review-actions { display: flex; gap: 0.5rem; flex-wrap: wrap; padding-top: 1rem; border-top: 1px solid var(--border); }
.review-actions form { display: inline; }
.review-status-badge { display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; font-weight: 600; }
.review-status-badge.approved { background: rgba(34, 197, 94, 0.15); color: var(--success); }
.review-status-badge.pending { background: rgba(245, 158, 11, 0.15); color: var(--warning); }

/* Summary Grid */
.summary-grid { display: grid; grid-template-columns: 200px 1fr; gap: 2rem; align-items: center; }
@media (max-width: 600px) {
    .summary-grid { grid-template-columns: 1fr; gap: 1.5rem; }
}

/* Filter Pills */
.filter-pills-row { display: flex; gap: 0.5rem; flex-wrap: wrap; margin-bottom: 1.5rem; }
.filter-pill { display: inline-flex; align-items: center; gap: 0.35rem; padding: 0.5rem 1rem; background: var(--bg-card); border: 1px solid var(--border); border-radius: 50px; font-size: 0.85rem; color: var(--text-secondary); text-decoration: none; transition: all 0.2s; cursor: pointer; }
.filter-pill:hover { border-color: var(--primary); color: var(--primary); }
.filter-pill.active { background: linear-gradient(135deg, var(--primary) 0%, #FFD700 100%); border-color: transparent; color: #000; font-weight: 600; }
.filter-pill .count { background: rgba(255,255,255,0.3); padding: 2px 6px; border-radius: 50px; font-size: 0.7rem; font-weight: 700; }
.filter-pill:not(.active) .count { background: var(--bg-dark); color: var(--text-muted); }
</style>

<main class="main-content">
    <div class="page-header page-header-flex">
        <div>
            <h1><iconify-icon icon="solar:star-bold"></iconify-icon> Avaliações</h1>
            <p>Gerencie as avaliações dos seus produtos</p>
        </div>
    </div>

    <?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType; ?>">
        <iconify-icon icon="<?php echo $messageType === 'success' ? 'solar:check-circle-bold' : ($messageType === 'warning' ? 'solar:danger-triangle-bold' : 'solar:danger-circle-bold'); ?>"></iconify-icon>
        <?php echo $message; ?>
    </div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="background: var(--primary-light); color: var(--primary);">
                <iconify-icon icon="solar:star-bold"></iconify-icon>
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['total']; ?></span>
                <span class="stat-label">Total de Avaliações</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background: rgba(34, 197, 94, 0.1); color: #22C55E;">
                <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['approved']; ?></span>
                <span class="stat-label">Aprovadas</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background: rgba(245, 158, 11, 0.1); color: #F59E0B;">
                <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['pending']; ?></span>
                <span class="stat-label">Pendentes</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background: rgba(251, 191, 36, 0.1); color: #fbbf24;">
                <iconify-icon icon="solar:stars-bold"></iconify-icon>
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo number_format($stats['avg_rating'], 1); ?></span>
                <span class="stat-label">Nota Média</span>
            </div>
        </div>
    </div>

    <!-- Rating Distribution -->
    <?php if ($stats['total'] > 0): ?>
    <div class="card">
        <div class="card-header">
            <h3 style="font-size: 1.1rem; font-weight: 600;">Distribuição de Notas</h3>
        </div>
        <div class="summary-grid">
            <div class="big-rating">
                <div class="big-rating-number"><?php echo number_format($stats['avg_rating'], 1); ?></div>
                <div class="stars" style="justify-content: center; margin-top: 8px;">
                    <?php for ($i = 1; $i <= 5; $i++): ?>
                    <iconify-icon icon="<?php echo $i <= round($stats['avg_rating']) ? 'solar:star-bold' : 'solar:star-linear'; ?>" class="<?php echo $i <= round($stats['avg_rating']) ? 'filled' : 'empty'; ?>"></iconify-icon>
                    <?php endfor; ?>
                </div>
                <div class="big-rating-count"><?php echo $stats['total']; ?> avaliação<?php echo $stats['total'] != 1 ? 'ões' : ''; ?></div>
            </div>
            <div class="rating-bars">
                <?php for ($i = 5; $i >= 1; $i--):
                    $cnt = $ratingDist[$i] ?? 0;
                    $pct = $stats['total'] > 0 ? ($cnt / $stats['total'] * 100) : 0;
                ?>
                <div class="rating-bar-row">
                    <span class="rating-bar-label"><?php echo $i; ?> <iconify-icon icon="solar:star-bold" style="color: #fbbf24; font-size: 0.85rem;"></iconify-icon></span>
                    <div class="rating-bar-track"><div class="rating-bar-fill" style="width: <?php echo $pct; ?>%"></div></div>
                    <span class="rating-bar-count"><?php echo $cnt; ?></span>
                </div>
                <?php endfor; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Filters -->
    <div class="filter-pills-row">
        <a href="?<?php echo http_build_query(array_merge($_GET, ['status' => '', 'page' => 1])); ?>" class="filter-pill <?php echo !$statusFilter ? 'active' : ''; ?>">
            <iconify-icon icon="solar:list-bold"></iconify-icon> Todas <span class="count"><?php echo $stats['total']; ?></span>
        </a>
        <a href="?<?php echo http_build_query(array_merge($_GET, ['status' => 'approved', 'page' => 1])); ?>" class="filter-pill <?php echo $statusFilter === 'approved' ? 'active' : ''; ?>">
            <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Aprovadas <span class="count"><?php echo $stats['approved']; ?></span>
        </a>
        <a href="?<?php echo http_build_query(array_merge($_GET, ['status' => 'pending', 'page' => 1])); ?>" class="filter-pill <?php echo $statusFilter === 'pending' ? 'active' : ''; ?>">
            <iconify-icon icon="solar:clock-circle-bold"></iconify-icon> Pendentes <span class="count"><?php echo $stats['pending']; ?></span>
        </a>
        <?php for ($i = 5; $i >= 1; $i--): ?>
        <a href="?<?php echo http_build_query(array_merge($_GET, ['rating' => $i, 'page' => 1])); ?>" class="filter-pill <?php echo $ratingFilter === $i ? 'active' : ''; ?>">
            <?php echo $i; ?> <iconify-icon icon="solar:star-bold" style="font-size: 0.85rem;"></iconify-icon>
        </a>
        <?php endfor; ?>
    </div>

    <!-- Search -->
    <form method="GET" class="filter-bar" style="margin-bottom: 1.5rem;">
        <?php if ($statusFilter): ?><input type="hidden" name="status" value="<?php echo htmlspecialchars($statusFilter); ?>"><?php endif; ?>
        <?php if ($ratingFilter): ?><input type="hidden" name="rating" value="<?php echo $ratingFilter; ?>"><?php endif; ?>
        <div class="search-box" style="flex: 1; max-width: 400px;">
            <input type="text" name="search" class="form-input" placeholder="Buscar por nome, produto ou comentário..." value="<?php echo htmlspecialchars($searchFilter); ?>">
        </div>
        <button type="submit" class="btn btn-primary btn-sm"><iconify-icon icon="solar:magnifer-bold"></iconify-icon> Buscar</button>
        <?php if ($searchFilter): ?>
        <a href="?<?php echo http_build_query(array_diff_key($_GET, ['search' => ''])); ?>" class="btn btn-secondary btn-sm"><iconify-icon icon="solar:close-circle-bold"></iconify-icon></a>
        <?php endif; ?>
    </form>

    <!-- Reviews List -->
    <?php if (empty($reviews)): ?>
    <div class="empty-state">
        <iconify-icon icon="solar:star-bold"></iconify-icon>
        <h3>Nenhuma avaliação encontrada</h3>
        <p>Quando seus clientes avaliarem seus produtos, as avaliações aparecerão aqui.</p>
    </div>
    <?php else: ?>
        <?php foreach ($reviews as $review):
            $photos = !empty($review['photos']) ? json_decode($review['photos'], true) : [];
            if (!is_array($photos)) $photos = [];
        ?>
        <div class="review-card">
            <div class="review-card-header">
                <div class="review-author-info">
                    <div class="review-avatar"><?php echo strtoupper(substr($review['author_name'] ?? 'A', 0, 1)); ?></div>
                    <div>
                        <div class="review-author-name"><?php echo htmlspecialchars($review['author_name'] ?? 'Anônimo'); ?></div>
                        <?php if (!empty($review['author_email'])): ?>
                        <div class="review-author-email"><?php echo htmlspecialchars($review['author_email']); ?></div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="review-meta">
                    <div class="stars">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                        <iconify-icon icon="<?php echo $i <= $review['rating'] ? 'solar:star-bold' : 'solar:star-linear'; ?>" class="<?php echo $i <= $review['rating'] ? 'filled' : 'empty'; ?>"></iconify-icon>
                        <?php endfor; ?>
                    </div>
                    <span class="review-status-badge <?php echo $review['is_approved'] ? 'approved' : 'pending'; ?>">
                        <iconify-icon icon="<?php echo $review['is_approved'] ? 'solar:check-circle-bold' : 'solar:clock-circle-bold'; ?>"></iconify-icon>
                        <?php echo $review['is_approved'] ? 'Aprovada' : 'Pendente'; ?>
                    </span>
                    <span class="review-date"><?php echo date('d/m/Y H:i', strtotime($review['created_at'])); ?></span>
                </div>
            </div>

            <div class="review-product">
                <?php if (!empty($review['product_image'])): ?>
                <img src="<?php echo htmlspecialchars($review['product_image']); ?>" alt="" class="review-product-img" onerror="this.style.display='none'">
                <?php else: ?>
                <div class="review-product-img" style="display:flex;align-items:center;justify-content:center;"><iconify-icon icon="solar:bag-bold" style="font-size:1.5rem;color:var(--text-muted);"></iconify-icon></div>
                <?php endif; ?>
                <div class="review-product-name"><?php echo htmlspecialchars($review['product_name'] ?? 'Produto removido'); ?></div>
            </div>

            <?php if (!empty($review['comment'])): ?>
            <div class="review-comment"><?php echo nl2br(htmlspecialchars($review['comment'])); ?></div>
            <?php endif; ?>

            <?php if (!empty($photos)): ?>
            <div class="review-photos">
                <?php foreach ($photos as $photo): ?>
                <img src="<?php echo htmlspecialchars($photo); ?>" alt="Foto da avaliação" class="review-photo" onclick="window.open(this.src, '_blank')" onerror="this.style.display='none'">
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <div class="review-actions">
                <?php if (!$review['is_approved']): ?>
                <form method="POST">
                    <input type="hidden" name="action" value="approve">
                    <input type="hidden" name="review_id" value="<?php echo $review['id']; ?>">
                    <button type="submit" class="btn btn-sm" style="background:rgba(34,197,94,0.15);color:var(--success);border:1px solid rgba(34,197,94,0.3);">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Aprovar
                    </button>
                </form>
                <?php else: ?>
                <form method="POST">
                    <input type="hidden" name="action" value="reject">
                    <input type="hidden" name="review_id" value="<?php echo $review['id']; ?>">
                    <button type="submit" class="btn btn-sm" style="background:rgba(245,158,11,0.15);color:var(--warning);border:1px solid rgba(245,158,11,0.3);">
                        <iconify-icon icon="solar:close-circle-bold"></iconify-icon> Rejeitar
                    </button>
                </form>
                <?php endif; ?>
                <form method="POST" onsubmit="return confirm('Tem certeza que deseja excluir esta avaliação?');">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="review_id" value="<?php echo $review['id']; ?>">
                    <button type="submit" class="btn btn-sm" style="background:rgba(239,68,68,0.15);color:var(--error);border:1px solid rgba(239,68,68,0.3);">
                        <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon> Excluir
                    </button>
                </form>
            </div>
        </div>
        <?php endforeach; ?>

        <?php if ($totalPages > 1): ?>
        <div style="display: flex; justify-content: center; gap: 0.5rem; margin-top: 1.5rem;">
            <?php if ($page > 1): ?>
            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" class="btn btn-secondary btn-sm"><iconify-icon icon="solar:arrow-left-bold"></iconify-icon></a>
            <?php endif; ?>
            <span style="padding: 0.5rem 1rem;">Página <?php echo $page; ?> de <?php echo $totalPages; ?></span>
            <?php if ($page < $totalPages): ?>
            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" class="btn btn-secondary btn-sm"><iconify-icon icon="solar:arrow-right-bold"></iconify-icon></a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    <?php endif; ?>
</main>

<?php include __DIR__ . '/../includes/dashboard-footer.php'; ?>
