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

// Provera da li je korisnik prijavljen kao admin
if (!is_admin()) {
    header('Location: /admin/login.php');
    exit;
}

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

// Pretraga
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Filteri
$parent_id = isset($_GET['parent']) ? intval($_GET['parent']) : 0;

// Izgradnja upita
$conditions = [];
$params = [];

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

if ($parent_id > 0) {
    $conditions[] = "c.parent_id = ?";
    $params[] = $parent_id;
} else if ($parent_id === 0 && isset($_GET['parent'])) {
    // Ako je parent=0, prikažite samo root kategorije
    $conditions[] = "c.parent_id IS NULL";
}

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

// Ukupan broj kategorija
$count_sql = "SELECT COUNT(*) as count FROM categories c {$where_clause}";
$total_categories = get_row($count_sql, $params)['count'];
$total_pages = ceil($total_categories / $items_per_page);

// Dohvatanje kategorija
$sql = "
    SELECT 
        c.*,
        p.name as parent_name,
        (SELECT COUNT(*) FROM product_categories pc WHERE pc.category_id = c.id) as product_count
    FROM categories c
    LEFT JOIN categories p ON c.parent_id = p.id
    {$where_clause}
    ORDER BY c.name ASC
    LIMIT {$offset}, {$items_per_page}
";

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

// Dohvatanje roditeljskih kategorija za filter
$parent_categories = get_rows("SELECT id, name FROM categories WHERE parent_id IS NULL ORDER BY name ASC");

// Naslov stranice
$page_title = 'Kategorije';

// Uključivanje header-a
require_once '../includes/header.php';
?>

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Kategorije</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/admin/">Kontrolna tabla</a></li>
                    <li class="breadcrumb-item active">Kategorije</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<section class="content">
    <div class="container-fluid">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Lista kategorija</h3>
                <div class="card-tools">
                    <a href="/admin/categories/add.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Dodaj kategoriju
                    </a>
                </div>
            </div>
            
            <div class="card-body">
                <!-- Filteri -->
                <form action="" method="get" class="mb-4">
                    <div class="row">
                        <div class="col-md-5">
                            <div class="form-group">
                                <input type="text" name="search" class="form-control" placeholder="Pretraži kategorije..." value="<?php echo htmlspecialchars($search); ?>">
                            </div>
                        </div>
                        <div class="col-md-5">
                            <div class="form-group">
                                <select name="parent" class="form-control">
                                    <option value="">Sve kategorije</option>
                                    <option value="0" <?php echo isset($_GET['parent']) && $_GET['parent'] === '0' ? 'selected' : ''; ?>>Samo glavne kategorije</option>
                                    <?php foreach ($parent_categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>" <?php echo $parent_id == $cat['id'] ? 'selected' : ''; ?>>
                                        Podkategorije od: <?php echo $cat['name']; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <button type="submit" class="btn btn-primary btn-block">Filtriraj</button>
                            </div>
                        </div>
                    </div>
                </form>
                
                <!-- Tabela kategorija -->
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Slika</th>
                                <th>Naziv</th>
                                <th>Slug</th>
                                <th>Roditeljska kategorija</th>
                                <th>Broj proizvoda</th>
                                <th>Akcije</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($categories)): ?>
                            <tr>
                                <td colspan="7" class="text-center">Nema pronađenih kategorija</td>
                            </tr>
                            <?php else: ?>
                                <?php foreach ($categories as $category): ?>
                                <tr>
                                    <td><?php echo $category['id']; ?></td>
                                    <td>
                                        <?php if (!empty($category['image'])): ?>
                                        <img src="<?php echo UPLOADS_URL . '/categories/' . $category['image']; ?>" alt="<?php echo $category['name']; ?>" width="50">
                                        <?php else: ?>
                                        <img src="/assets/images/no-image.jpg" alt="Nema slike" width="50">
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo $category['name']; ?></td>
                                    <td><?php echo $category['slug']; ?></td>
                                    <td><?php echo $category['parent_name'] ?: 'Glavna kategorija'; ?></td>
                                    <td><?php echo $category['product_count']; ?></td>
                                    <td>
                                        <a href="/category.php?category=<?php echo $category['slug']; ?>" class="btn btn-info btn-sm" target="_blank">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="/admin/categories/edit.php?id=<?php echo $category['id']; ?>" class="btn btn-primary btn-sm">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="/admin/categories/delete.php?id=<?php echo $category['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Da li ste sigurni da želite da obrišete ovu kategoriju?');">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Paginacija -->
                <?php if ($total_pages > 1): ?>
                <div class="mt-4">
                    <ul class="pagination justify-content-center">
                        <?php if ($current_page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo $current_page - 1; ?>&search=<?php echo urlencode($search); ?>&parent=<?php echo $parent_id; ?>">
                                Prethodna
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <?php
                        $start_page = max(1, $current_page - 2);
                        $end_page = min($total_pages, $current_page + 2);
                        
                        for ($i = $start_page; $i <= $end_page; $i++):
                        ?>
                        <li class="page-item <?php echo $i == $current_page ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&parent=<?php echo $parent_id; ?>">
                                <?php echo $i; ?>
                            </a>
                        </li>
                        <?php endfor; ?>
                        
                        <?php if ($current_page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo $current_page + 1; ?>&search=<?php echo urlencode($search); ?>&parent=<?php echo $parent_id; ?>">
                                Sledeća
                            </a>
                        </li>
                        <?php endif; ?>
                    </ul>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

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