<?php
/**
 * Products API
 * GET    /api/products.php         - Get all products
 * GET    /api/products.php?id=xxx  - Get single product
 * POST   /api/products.php         - Create product (auth required)
 * PUT    /api/products.php?id=xxx  - Update product (auth required)
 * DELETE /api/products.php?id=xxx  - Delete product (auth required)
 */

require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? null;
$db = getDB();

// GET - List all or single product
if ($method === 'GET') {
    if ($id) {
        // Get single product by ID or slug
        $stmt = $db->prepare("SELECT * FROM products WHERE id = ? OR slug = ?");
        $stmt->execute([$id, $id]);
        $product = $stmt->fetch();
        
        if (!$product) {
            errorResponse('Product tidak ditemukan', 404);
        }
        
        // Decode images JSON
        $product['images'] = json_decode($product['images'], true) ?? [];
        $product['is_available'] = (bool)$product['is_available'];
        $product['featured'] = (bool)$product['featured'];
        
        jsonResponse($product);
    } else {
        // Get all products
        $category = $_GET['category'] ?? null;
        $featured = isset($_GET['featured']) ? $_GET['featured'] : null;
        $limit = (int)($_GET['limit'] ?? 100);
        
        $sql = "SELECT * FROM products WHERE 1=1";
        $params = [];
        
        if ($category) {
            $sql .= " AND category = ?";
            $params[] = $category;
        }
        
        if ($featured !== null) {
            $sql .= " AND featured = ?";
            $params[] = $featured === 'true' || $featured === '1' ? 1 : 0;
        }
        
        $sql .= " ORDER BY created_at DESC LIMIT $limit";
        
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $products = $stmt->fetchAll();
        
        // Decode images for each product
        foreach ($products as &$product) {
            $product['images'] = json_decode($product['images'], true) ?? [];
            $product['is_available'] = (bool)$product['is_available'];
            $product['featured'] = (bool)$product['featured'];
        }
        
        jsonResponse($products);
    }
}

// POST - Create new product
if ($method === 'POST') {
    requireAuth();
    $input = getJsonInput();
    
    $name = $input['name'] ?? '';
    if (empty($name)) {
        errorResponse('Nama product harus diisi', 400);
    }
    
    $slug = !empty($input['slug']) ? $input['slug'] : generateSlug($name);
    
    // Check duplicate slug
    $stmt = $db->prepare("SELECT id FROM products WHERE slug = ?");
    $stmt->execute([$slug]);
    if ($stmt->fetch()) {
        $slug = $slug . '-' . substr(generateUUID(), 0, 8);
    }
    
    $id = generateUUID();
    $description = $input['description'] ?? '';
    $price = (float)($input['price'] ?? 0);
    $originalPrice = (float)($input['original_price'] ?? 0);
    $category = $input['category'] ?? 'Spareparts';
    $brand = $input['brand'] ?? '';
    $images = json_encode($input['images'] ?? []);
    $stock = (int)($input['stock'] ?? 0);
    $isAvailable = isset($input['is_available']) ? ($input['is_available'] ? 1 : 0) : 1;
    $featured = isset($input['featured']) ? ($input['featured'] ? 1 : 0) : 0;
    
    $stmt = $db->prepare("
        INSERT INTO products (id, name, slug, description, price, original_price, category, brand, images, stock, is_available, featured)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([$id, $name, $slug, $description, $price, $originalPrice, $category, $brand, $images, $stock, $isAvailable, $featured]);
    
    // Return created product
    $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$id]);
    $product = $stmt->fetch();
    $product['images'] = json_decode($product['images'], true) ?? [];
    $product['is_available'] = (bool)$product['is_available'];
    $product['featured'] = (bool)$product['featured'];
    
    jsonResponse($product, 201);
}

// PUT - Update product
if ($method === 'PUT') {
    requireAuth();
    
    if (!$id) {
        errorResponse('ID harus disertakan', 400);
    }
    
    $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$id]);
    $product = $stmt->fetch();
    
    if (!$product) {
        errorResponse('Product tidak ditemukan', 404);
    }
    
    $input = getJsonInput();
    
    $name = $input['name'] ?? $product['name'];
    $slug = $input['slug'] ?? $product['slug'];
    $description = $input['description'] ?? $product['description'];
    $price = isset($input['price']) ? (float)$input['price'] : $product['price'];
    $originalPrice = isset($input['original_price']) ? (float)$input['original_price'] : $product['original_price'];
    $category = $input['category'] ?? $product['category'];
    $brand = $input['brand'] ?? $product['brand'];
    $images = isset($input['images']) ? json_encode($input['images']) : $product['images'];
    $stock = isset($input['stock']) ? (int)$input['stock'] : $product['stock'];
    $isAvailable = isset($input['is_available']) ? ($input['is_available'] ? 1 : 0) : $product['is_available'];
    $featured = isset($input['featured']) ? ($input['featured'] ? 1 : 0) : $product['featured'];
    
    $stmt = $db->prepare("
        UPDATE products 
        SET name = ?, slug = ?, description = ?, price = ?, original_price = ?, 
            category = ?, brand = ?, images = ?, stock = ?, is_available = ?, featured = ?, updated_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$name, $slug, $description, $price, $originalPrice, $category, $brand, $images, $stock, $isAvailable, $featured, $id]);
    
    // Return updated product
    $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$id]);
    $product = $stmt->fetch();
    $product['images'] = json_decode($product['images'], true) ?? [];
    $product['is_available'] = (bool)$product['is_available'];
    $product['featured'] = (bool)$product['featured'];
    
    jsonResponse($product);
}

// DELETE - Delete product
if ($method === 'DELETE') {
    requireAuth();
    
    if (!$id) {
        errorResponse('ID harus disertakan', 400);
    }
    
    $stmt = $db->prepare("SELECT id FROM products WHERE id = ?");
    $stmt->execute([$id]);
    
    if (!$stmt->fetch()) {
        errorResponse('Product tidak ditemukan', 404);
    }
    
    $db->prepare("DELETE FROM products WHERE id = ?")->execute([$id]);
    
    jsonResponse(['message' => 'Product berhasil dihapus']);
}

errorResponse('Method not allowed', 405);
