<?php
/**
 * Admin Reviews Management
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Reviews';

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $review_id = (int)$_POST['review_id'];
    $status = sanitize($_POST['status']);
    
    try {
        $stmt = $pdo->prepare("UPDATE reviews SET status = ? WHERE id = ?");
        $stmt->execute([$status, $review_id]);
        
        // Update product rating
        $stmt = $pdo->prepare("SELECT product_id FROM reviews WHERE id = ?");
        $stmt->execute([$review_id]);
        $review = $stmt->fetch();
        if ($review) {
            update_product_rating($review['product_id']);
        }
        
        set_flash_message('Review status updated!', 'success');
    } catch (PDOException $e) {
        set_flash_message('Failed to update status.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        // Get product_id before delete
        $stmt = $pdo->prepare("SELECT product_id FROM reviews WHERE id = ?");
        $stmt->execute([$id]);
        $review = $stmt->fetch();
        
        $stmt = $pdo->prepare("DELETE FROM reviews WHERE id = ?");
        $stmt->execute([$id]);
        
        // Update product rating
        if ($review) {
            update_product_rating($review['product_id']);
        }
        
        set_flash_message('Review deleted successfully!', 'success');
    } catch (PDOException $e) {
        set_flash_message('Failed to delete review.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Pagination
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Filters
$status_filter = sanitize($_GET['status'] ?? '');

// Build query
$sql = "SELECT r.*, p.name as product_name, u.name as user_name 
        FROM reviews r 
        JOIN products p ON r.product_id = p.id 
        JOIN users u ON r.user_id = u.id 
        WHERE 1=1";
$count_sql = "SELECT COUNT(*) FROM reviews r WHERE 1=1";
$params = [];

if ($status_filter) {
    $sql .= " AND r.status = ?";
    $count_sql .= " AND r.status = ?";
    $params[] = $status_filter;
}

$sql .= " ORDER BY r.created_at DESC LIMIT ? OFFSET ?";

// Get total count
$stmt = $pdo->prepare($count_sql);
$stmt->execute($params);
$total_reviews = $stmt->fetchColumn();
$total_pages = ceil($total_reviews / $per_page);

// Get reviews
$stmt = $pdo->prepare($sql);
$stmt->execute(array_merge($params, [$per_page, $offset]));
$reviews = $stmt->fetchAll();

include __DIR__ . '/includes/header.php';
?>

<div class="admin-content">
    <div class="admin-header d-flex justify-content-between align-items-center">
        <h1><i class="fas fa-star me-2"></i>Reviews</h1>
    </div>
    
    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-4">
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="approved" <?php echo $status_filter === 'approved' ? 'selected' : ''; ?>>Approved</option>
                        <option value="rejected" <?php echo $status_filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter me-2"></i>Filter
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Reviews Table -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Customer</th>
                            <th>Rating</th>
                            <th>Review</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($reviews as $review): ?>
                        <tr>
                            <td>
                                <a href="<?php echo BASE_URL; ?>/product.php?slug=<?php echo slugify($review['product_name']); ?>" target="_blank">
                                    <?php echo sanitize($review['product_name']); ?>
                                </a>
                            </td>
                            <td><?php echo sanitize($review['user_name']); ?></td>
                            <td>
                                <div class="text-warning">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <i class="fas fa-star<?php echo $i <= $review['rating'] ? '' : '-o'; ?>"></i>
                                    <?php endfor; ?>
                                </div>
                            </td>
                            <td>
                                <?php echo truncate(sanitize($review['review']), 100); ?>
                            </td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo match($review['status']) {
                                        'approved' => 'success',
                                        'pending' => 'warning',
                                        'rejected' => 'danger',
                                        default => 'secondary'
                                    };
                                ?>">
                                    <?php echo ucfirst($review['status']); ?>
                                </span>
                            </td>
                            <td><?php echo format_date($review['created_at']); ?></td>
                            <td>
                                <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#reviewModal<?php echo $review['id']; ?>">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <a href="?delete=<?php echo $review['id']; ?>" class="btn btn-sm btn-danger confirm-delete">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        
                        <!-- Review Modal -->
                        <div class="modal fade" id="reviewModal<?php echo $review['id']; ?>" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content bg-dark">
                                    <div class="modal-header">
                                        <h5 class="modal-title">Review Details</h5>
                                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <div class="mb-3">
                                            <label class="form-label">Product</label>
                                            <input type="text" class="form-control" value="<?php echo sanitize($review['product_name']); ?>" disabled>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Customer</label>
                                            <input type="text" class="form-control" value="<?php echo sanitize($review['user_name']); ?>" disabled>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Rating</label>
                                            <div class="text-warning fs-5">
                                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                                    <i class="fas fa-star<?php echo $i <= $review['rating'] ? '' : '-o'; ?>"></i>
                                                <?php endfor; ?>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Review</label>
                                            <textarea class="form-control" rows="4" disabled><?php echo sanitize($review['review']); ?></textarea>
                                        </div>
                                        
                                        <form method="POST">
                                            <input type="hidden" name="review_id" value="<?php echo $review['id']; ?>">
                                            <div class="mb-3">
                                                <label class="form-label">Status</label>
                                                <select name="status" class="form-select">
                                                    <option value="pending" <?php echo $review['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                                    <option value="approved" <?php echo $review['status'] === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                                    <option value="rejected" <?php echo $review['status'] === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                                </select>
                                            </div>
                                            <button type="submit" name="update_status" class="btn btn-primary">Update Status</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="card-footer">
            <nav>
                <ul class="pagination justify-content-center mb-0">
                    <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&status=<?php echo $status_filter; ?>">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>
                    <?php endif; ?>
                    
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $status_filter; ?>"><?php echo $i; ?></a>
                    </li>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&status=<?php echo $status_filter; ?>">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
    </div>
</div>

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