<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_auth(['admin']);

header('Content-Type: application/json');

try {
    $pdo = hw_db();
    
    // Get pagination parameters
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $offset = ($page - 1) * $limit;
    
    // Get search parameter
    $search = isset($_GET['search']) ? '%' . $_GET['search'] . '%' : '%';
    
    // Optional active filter
    $hasActiveFilter = isset($_GET['active']) && $_GET['active'] !== '';
    $activeFilter = $hasActiveFilter ? (int)$_GET['active'] : null;

    // Get total count
    if ($hasActiveFilter) {
        $countStmt = $pdo->prepare('SELECT COUNT(*) as total FROM products WHERE name LIKE ? AND active = ?');
        $countStmt->execute([$search, $activeFilter]);
    } else {
        $countStmt = $pdo->prepare('SELECT COUNT(*) as total FROM products WHERE name LIKE ?');
        $countStmt->execute([$search]);
    }
    $total = $countStmt->fetch()['total'];
    
    // Get products with category info
    $sql = '
        SELECT 
            p.id,
            p.name,
            p.description,
            p.price,
            p.stock_quantity,
            p.sku,
            p.image_url,
            p.active,
            pc.name as category_name,
            p.created_at
        FROM products p
        LEFT JOIN product_categories pc ON p.category_id = pc.id
        WHERE p.name LIKE ?
    ';
    $params = [$search];
    if ($hasActiveFilter) {
        $sql .= ' AND p.active = ?';
        $params[] = $activeFilter;
    }
    $sql .= ' ORDER BY p.created_at DESC LIMIT ? OFFSET ?';
    $params[] = $limit;
    $params[] = $offset;

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'products' => $products,
        'pagination' => [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'pages' => ceil($total / $limit)
        ]
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to load products: ' . $e->getMessage()
    ]);
}
