<?php
require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../includes/admin-functions.php';

// Check admin login
if (!is_admin()) {
    header('Location: /admin/login.php');
    exit;
}

// Pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Filters
$status = isset($_GET['status']) ? $_GET['status'] : '';
$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Build query conditions
$conditions = [];
$params = [];

if (!empty($status) && in_array($status, ['approved', 'pending', 'rejected'])) {
    $conditions[] = "r.status = ?";
    $params[] = $status;
}

if (!empty($product_id)) {
    $conditions[] = "r.product_id = ?";
    $params[] = $product_id;
}

if (!empty($search)) {
    $conditions[] = "(r.name LIKE ? OR r.comment LIKE ?)";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
}

$where_clause = !empty($conditions) ? "WHERE " . implode(" AND ", $conditions) : "";

// Count total reviews
$total_reviews_query = "SELECT COUNT(*) as count FROM reviews r $where_clause";
$total_reviews = get_row($total_reviews_query, $params)['count'];

// Get reviews for current page
$sql = "
    SELECT 
        r.id, r.name, r.email, r.rating, 
        r.comment, r.status, r.created_at,
        p.name as product_name
    FROM 
        reviews r
    JOIN 
        products p ON r.product_id = p.id
    $where_clause
    ORDER BY r.created_at DESC
    LIMIT ? OFFSET ?
";

$params[] = $per_page;
$params[] = $offset;

$reviews = get_rows($sql, $params);

// Get list of products for filter
$products = get_rows("SELECT id, name FROM products ORDER BY name ASC");

// Prepare page metadata
$title = 'Recenzije - Admin';
require_once '../includes/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-4">Pregled recenzija</h1>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="get" action="">
                <div class="row">
                    <div class="col-md-3">
                        <input type="text" name="search" class="form-control" 
                               placeholder="Pretraga (ime, sadržaj)" 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-md-2">
                        <select name="status" class="form-control">
                            <option value="">Svi statusi</option>
                            <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>Na čekanju</option>
                            <option value="approved" <?php echo $status == 'approved' ? 'selected' : ''; ?>>Odobrene</option>
                            <option value="rejected" <?php echo $status == 'rejected' ? 'selected' : ''; ?>>Odbijene</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select name="product_id" class="form-control">
                            <option value="">Svi proizvodi</option>
                            <?php foreach ($products as $product): ?>
                                <option value="<?php echo $product['id']; ?>" 
                                    <?php echo $product_id == $product['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($product['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary">Pretraži</button>
                        <a href="?" class="btn btn-secondary">Resetuj</a>
                    </div>
                    
                </div>
            </form>
        </div>
    </div>

    <!-- Reviews Table -->
    <div class="card">
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Ime</th>
                        <th>Proizvod</th>
                        <th>Ocena</th>
                        <th>Sadržaj</th>
                        <th>Status</th>
                        <th>Datum</th>
                        <th>Akcije</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($reviews as $review): ?>
                    <tr>
                        <td><?php echo $review['id']; ?></td>
                        <td><?php echo htmlspecialchars($review['name']); ?></td>
                        <td><?php echo htmlspecialchars($review['product_name']); ?></td>
                        <td>
                            <?php 
                            for ($i = 1; $i <= 5; $i++) {
                                echo $i <= $review['rating'] ? '★' : '☆';
                            }
                            ?>
                        </td>
                        <td title="<?php echo htmlspecialchars($review['comment']); ?>">
                            <?php echo substr(htmlspecialchars($review['comment']), 0, 50) . '...'; ?>
                        </td>
                        <td>
                            <span class="badge 
                                <?php 
                                switch ($review['status']) {
                                    case 'pending': echo 'badge-warning'; break;
                                    case 'approved': echo 'badge-success'; break;
                                    case 'rejected': echo 'badge-danger'; break;
                                }
                                ?>">
                                <?php 
                                switch ($review['status']) {
                                    case 'pending': echo 'Na čekanju'; break;
                                    case 'approved': echo 'Odobrena'; break;
                                    case 'rejected': echo 'Odbijena'; break;
                                }
                                ?>
                            </span>
                        </td>
                        <td><?php echo date('d.m.Y', strtotime($review['created_at'])); ?></td>
                        <td>
                            <div class="btn-group">
                                <a href="edit.php?id=<?php echo $review['id']; ?>" class="btn btn-sm btn-primary">Uredi</a>
                                <button class="btn btn-sm btn-danger delete-review" data-id="<?php echo $review['id']; ?>">Obriši</button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Pagination -->
    <?php 
    $total_pages = ceil($total_reviews / $per_page);
    include '../includes/pagination.php'; 
    ?>
</div>

<!-- Delete Review Modal -->
<div class="modal fade" id="deleteReviewModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Potvrda brisanja recenzije</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                Da li ste sigurni da želite da obrišete ovu recenziju?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Otkaži</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteReview">Obriši</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let reviewToDelete = null;

    // Delete review button click
    document.querySelectorAll('.delete-review').forEach(button => {
        button.addEventListener('click', function() {
            reviewToDelete = this.getAttribute('data-id');
            $('#deleteReviewModal').modal('show');
        });
    });

    // Confirm delete button
    document.getElementById('confirmDeleteReview').addEventListener('click', function() {
        if (reviewToDelete) {
            window.location.href = 'delete.php?id=' + reviewToDelete;
        }
    });
});
</script>

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