<?php
/**
 * Manage Reviews & Comments (Premium Light Green UI)
 */
require_once 'header.php';

$success = '';
$error = '';

// Self-Healing Database: Ensure product_comments table exists
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS product_comments (
        id INT AUTO_INCREMENT PRIMARY KEY,
        product_id INT NOT NULL,
        user_id INT NULL,
        user_name VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
        parent_id INT NULL,
        rating INT DEFAULT 5,
        comment TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
        is_admin_reply TINYINT(1) DEFAULT 0,
        status ENUM('active', 'inactive') DEFAULT 'active',
        is_pinned TINYINT(1) DEFAULT 0,
        likes INT DEFAULT 0,
        dislikes INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
} catch (PDOException $e) {}

// ==========================================
// Actions Logic (Delete, Toggle Status, Pin)
// ==========================================
if (isset($_GET['action']) && isset($_GET['id'])) {
    $action = $_GET['action'];
    $comment_id = (int)$_GET['id'];

    try {
        if ($action === 'delete') {
            // Delete comment and its replies
            $stmt = $pdo->prepare("DELETE FROM product_comments WHERE id = ? OR parent_id = ?");
            $stmt->execute([$comment_id, $comment_id]);
            $success = "Review has been permanently deleted.";
        } elseif ($action === 'toggle_status') {
            $stmt = $pdo->prepare("UPDATE product_comments SET status = IF(status='active', 'inactive', 'active') WHERE id = ?");
            $stmt->execute([$comment_id]);
            $success = "Review visibility updated.";
        } elseif ($action === 'toggle_pin') {
            $stmt = $pdo->prepare("UPDATE product_comments SET is_pinned = IF(is_pinned=1, 0, 1) WHERE id = ?");
            $stmt->execute([$comment_id]);
            $success = "Review pin status updated.";
        }
    } catch (PDOException $e) {
        $error = "Action failed: " . $e->getMessage();
    }
}

// ==========================================
// Fetch All Reviews
// ==========================================
$query = "
    SELECT c.*, p.title as product_title, p.main_image 
    FROM product_comments c 
    LEFT JOIN products p ON c.product_id = p.id 
    ORDER BY c.id DESC
";
$reviews = $pdo->query($query)->fetchAll();
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
<style>
    :root {
        --primary: #84cc16; /* Light Green */
        --primary-hover: #65a30d;
        --bg-light: #f8fafc;
        --card-bg: #ffffff;
        --border: #e2e8f0;
        --text-main: #1e293b;
        --text-muted: #64748b;
    }

    body { background: var(--bg-light); color: var(--text-main); font-family: 'Inter', sans-serif; margin: 0; }
    
    .settings-container { max-width: 1200px; margin: 0 auto; padding: 20px; }

    /* ================= Header ================= */
    .page-header { 
        display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; flex-wrap: wrap; gap: 15px;
    }
    .page-title { font-size: 1.5rem; font-weight: 800; color: var(--text-main); margin: 0; }

    /* ================= Responsive Table Design ================= */
    .table-card { 
        background: var(--card-bg); border: 1px solid var(--border); border-radius: 12px; padding: 20px; box-shadow: none; margin-bottom: 30px;
    }
    
    .table-responsive { 
        width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; 
    }
    .data-table { width: 100%; border-collapse: collapse; text-align: left; min-width: 900px; }
    .data-table th { padding: 15px 12px; font-size: 0.8rem; color: var(--text-muted); font-weight: 700; border-bottom: 1px solid var(--border); text-transform: uppercase; white-space: nowrap; background: #fafafa;}
    .data-table td { padding: 15px 12px; border-bottom: 1px solid var(--border); font-size: 0.9rem; color: var(--text-main); font-weight: 500; vertical-align: top; }
    .data-table tr:last-child td { border-bottom: none; }
    .data-table tr:hover { background: #fdfdfd; }
    
    .prod-img { width: 40px; height: 40px; border-radius: 6px; object-fit: cover; border: 1px solid var(--border); padding: 2px; background: #fff;}

    /* ================= Badges & Buttons ================= */
    .status-badge { padding: 4px 10px; border-radius: 20px; font-size: 0.7rem; font-weight: 800; text-transform: uppercase; display: inline-block; white-space: nowrap;}
    .status-active { background: #ecfdf5; color: #10b981; border: 1px solid #a7f3d0; }
    .status-inactive { background: #f1f5f9; color: #64748b; border: 1px solid #cbd5e1; }
    
    .action-btn { font-size: 0.8rem; font-weight: 700; text-decoration: none; padding: 6px 12px; border-radius: 6px; transition: 0.2s; display: inline-flex; align-items: center; gap: 5px; white-space: nowrap;}
    .btn-toggle { color: #3b82f6; background: #eff6ff; border: 1px solid transparent; }
    .btn-toggle:hover { background: #dbeafe; border-color: #bfdbfe; }
    .btn-pin { color: #f59e0b; background: #fef3c7; border: 1px solid transparent; }
    .btn-pin:hover { background: #fde68a; border-color: #fcd34d; }
    .btn-delete { color: #ef4444; background: #fef2f2; border: 1px solid transparent; }
    .btn-delete:hover { background: #fee2e2; border-color: #fecaca; }

    .review-text { font-size: 0.9rem; color: var(--text-main); line-height: 1.5; max-width: 300px; white-space: normal; word-break: break-word;}
    .review-meta { font-size: 0.75rem; color: var(--text-muted); margin-top: 5px; }
    
    .stars { display: flex; align-items: center; gap: 2px; color: var(--primary); }
    .stars svg { width: 14px; height: 14px; fill: currentColor; }
    .stars-empty { color: #cbd5e1; }

    /* Toast */
    .toast-success { background: #10b981 !important; color: #fff !important; font-weight: 600; border-radius: 6px !important; box-shadow: none !important; border: 1px solid #059669 !important; padding: 10px 20px !important; }
    .toast-error { background: #ef4444 !important; color: #fff !important; font-weight: 600; border-radius: 6px !important; box-shadow: none !important; border: 1px solid #b91c1c !important; padding: 10px 20px !important; }

    /* ================= Mobile Adjustments ================= */
    @media (max-width: 768px) {
        .settings-container { padding: 15px 10px; }
        .page-header { flex-direction: column; align-items: flex-start; gap: 15px; }
        .table-card { padding: 15px 10px; }
        .data-table th, .data-table td { padding: 12px 10px; }
    }
</style>

<div class="settings-container">
    <div class="page-header">
        <h1 class="page-title">Manage Reviews & Comments</h1>
    </div>

    <div class="table-card">
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Date & Product</th>
                        <th>User & Rating</th>
                        <th>Review Details</th>
                        <th>Status</th>
                        <th style="text-align: right;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($reviews as $rev): ?>
                    <tr>
                        <td>
                            <div style="font-weight: 700; color: var(--text-main); font-size: 0.85rem; margin-bottom: 8px;">
                                <?php echo date('d M Y, h:i A', strtotime($rev['created_at'])); ?>
                            </div>
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <?php if(!empty($rev['main_image'])): ?>
                                    <img src="../uploads/products/images/<?php echo htmlspecialchars($rev['main_image']); ?>" class="prod-img" onerror="this.style.display='none';">
                                <?php endif; ?>
                                <div style="font-size: 0.85rem; font-weight: 600; color: var(--text-muted); max-width: 150px; white-space: normal;">
                                    <?php echo htmlspecialchars($rev['product_title'] ?? 'Unknown Product'); ?>
                                </div>
                            </div>
                        </td>
                        
                        <td>
                            <div style="font-weight: 700; color: var(--text-main); margin-bottom: 4px;">
                                <?php echo htmlspecialchars($rev['user_name']); ?>
                                <?php if($rev['is_admin_reply']): ?>
                                    <span style="font-size: 0.65rem; background: var(--primary); color: white; padding: 2px 6px; border-radius: 4px; margin-left: 5px;">ADMIN</span>
                                <?php endif; ?>
                            </div>
                            <?php if(!$rev['parent_id']): ?>
                                <div class="stars">
                                    <?php 
                                    for($i=1; $i<=5; $i++) {
                                        if($i <= $rev['rating']) {
                                            echo '<svg viewBox="0 0 24 24"><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/></svg>';
                                        } else {
                                            echo '<svg class="stars-empty" viewBox="0 0 24 24"><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/></svg>';
                                        }
                                    }
                                    ?>
                                </div>
                            <?php else: ?>
                                <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 600;">â†³ Reply</span>
                            <?php endif; ?>
                        </td>
                        
                        <td>
                            <div class="review-text">
                                <?php echo nl2br(htmlspecialchars($rev['comment'])); ?>
                            </div>
                            <div class="review-meta">
                                <?php if($rev['is_pinned']): ?>
                                    <span style="color: #f59e0b; font-weight: 700;">ðŸ“Œ Pinned</span> â€¢ 
                                <?php endif; ?>
                                ðŸ‘ <?php echo $rev['likes']; ?>  |  ðŸ‘Ž <?php echo $rev['dislikes']; ?>
                            </div>
                        </td>

                        <td>
                            <?php if($rev['status'] == 'active'): ?>
                                <span class="status-badge status-active">Active</span>
                            <?php else: ?>
                                <span class="status-badge status-inactive">Hidden</span>
                            <?php endif; ?>
                        </td>
                        
                        <td style="text-align: right;">
                            <div style="display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap;">
                                <a href="?action=toggle_status&id=<?php echo $rev['id']; ?>" class="action-btn btn-toggle" title="<?php echo $rev['status'] == 'active' ? 'Hide Review' : 'Show Review'; ?>">
                                    <?php if($rev['status'] == 'active'): ?>
                                        <svg width="14" height="14" viewBox="0 0 24 24"><path d="M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0-5C7.02 2 2.54 6.8 2 12c.54 5.2 5.02 10 10 10s9.46-4.8 10-10C21.46 6.8 16.98 2 12 2zm0 18c-4.2 0-7.85-3.08-8.82-7.18.97-4.1 4.62-7.18 8.82-7.18s7.85 3.08 8.82 7.18C19.85 16.92 16.2 20 12 20z"/></svg>
                                        Hide
                                    <?php else: ?>
                                        <svg width="14" height="14" viewBox="0 0 24 24"><path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/></svg>
                                        Show
                                    <?php endif; ?>
                                </a>

                                <?php if(!$rev['parent_id']): ?>
                                <a href="?action=toggle_pin&id=<?php echo $rev['id']; ?>" class="action-btn btn-pin">
                                    <svg width="14" height="14" viewBox="0 0 24 24"><path d="M16 12V4h1V2H7v2h1v8l-2 2v2h4v6h2v-6h4v-2l-2-2z"/></svg>
                                    <?php echo $rev['is_pinned'] ? 'Unpin' : 'Pin'; ?>
                                </a>
                                <?php endif; ?>

                                <a href="?action=delete&id=<?php echo $rev['id']; ?>" class="action-btn btn-delete" onclick="return confirm('Are you sure you want to permanently delete this review?');">
                                    <svg width="14" height="14" viewBox="0 0 24 24"><path d="M19 4h-3.5l-1-1h-5l-1 1H5v2h14M6 19a2 2 0 002 2h8a2 2 0 002-2V7H6v12z"/></svg>
                                    Del
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    
                    <?php if(empty($reviews)): ?>
                        <tr>
                            <td colspan="5" style="text-align: center; padding: 40px; color: var(--text-muted); font-weight: 500;">
                                No comments or reviews found.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
<script>
    <?php if($success): ?>
    Toastify({
        text: "<?php echo addslashes($success); ?>",
        duration: 3000,
        gravity: "top", 
        position: "center",
        className: "toast-success",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>

    <?php if($error): ?>
    Toastify({
        text: "<?php echo addslashes($error); ?>",
        duration: 4000,
        gravity: "top", 
        position: "center",
        className: "toast-error",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>
</script>

<?php require_once 'footer.php'; ?>
