<?php
/**
 * Tom's Java Jive - Products API
 */

require_once __DIR__ . '/../includes/functions.php';

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $productId = $_GET['id'] ?? null;
    
    if ($productId) {
        // Get single product
        $product = db()->fetch(
            "SELECT * FROM products WHERE product_id = :id AND is_active = 1",
            ['id' => $productId]
        );
        
        if (!$product) {
            jsonResponse(['error' => 'Product not found'], 404);
        }
        
        $product['images'] = json_decode($product['images'] ?? '[]', true);
        $product['tags'] = json_decode($product['tags'] ?? '[]', true);
        unset($product['id']);
        
        // Get reviews
        $reviews = db()->fetchAll(
            "SELECT review_id, customer_name, rating, title, comment, is_verified_purchase, created_at 
             FROM reviews WHERE product_id = :id AND is_approved = 1 ORDER BY created_at DESC",
            ['id' => $productId]
        );
        
        $product['reviews'] = $reviews;
        $product['average_rating'] = !empty($reviews) 
            ? round(array_sum(array_column($reviews, 'rating')) / count($reviews), 1) 
            : 0;
        
        jsonResponse($product);
    } else {
        // Get products list
        $category = $_GET['category'] ?? '';
        $search = $_GET['search'] ?? '';
        $featured = $_GET['featured'] ?? '';
        $limit = min(100, intval($_GET['limit'] ?? 20));
        $offset = intval($_GET['offset'] ?? 0);
        
        $where = ['is_active = 1'];
        $params = [];
        
        if ($category) {
            $where[] = 'category = :category';
            $params['category'] = $category;
        }
        
        if ($search) {
            $where[] = '(name LIKE :search OR description LIKE :search)';
            $params['search'] = '%' . $search . '%';
        }
        
        if ($featured === '1') {
            $where[] = 'is_featured = 1';
        }
        
        $whereClause = implode(' AND ', $where);
        
        $products = db()->fetchAll(
            "SELECT product_id, name, description, price, sale_price, category, images, stock, is_featured
             FROM products WHERE {$whereClause} 
             ORDER BY is_featured DESC, created_at DESC 
             LIMIT :limit OFFSET :offset",
            array_merge($params, ['limit' => $limit, 'offset' => $offset])
        );
        
        foreach ($products as &$p) {
            $p['images'] = json_decode($p['images'] ?? '[]', true);
        }
        
        $total = db()->count('products', $whereClause, $params);
        
        jsonResponse([
            'products' => $products,
            'total' => $total,
            'limit' => $limit,
            'offset' => $offset
        ]);
    }
}

jsonResponse(['error' => 'Method not allowed'], 405);
