<?php
// NEXUS Commerce - Seller Products Management API
require_once __DIR__ . '/db.php';

header('Content-Type: application/json; charset=utf-8');

$action = $_GET['action'] ?? ($_POST['action'] ?? 'list');

try {
    if ($action === 'list') {
        $stmt = $pdo->query("SELECT p.*, c.name as category_name FROM products p JOIN categories c ON p.category_id = c.id ORDER BY p.id DESC");
        $products = $stmt->fetchAll();
        echo json_encode(['status' => 'success', 'data' => $products]);
        exit;
    }

    if ($action === 'add') {
        $title = $_POST['title'] ?? 'New Product Item';
        $price = floatval($_POST['price'] ?? 990);
        $stock = intval($_POST['stock'] ?? 50);
        $category_id = intval($_POST['category_id'] ?? 1);
        $description = $_POST['description'] ?? 'Product description generated by Seller Assistant.';
        $sku = 'SKU-' . rand(1000, 9999);
        $img = $_POST['image_url'] ?? 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=600';

        $colors_raw = $_POST['colors'] ?? '';
        $sizes_raw = $_POST['sizes'] ?? '';

        $colors_arr = array_filter(array_map('trim', explode(',', $colors_raw)));
        $sizes_arr = array_filter(array_map('trim', explode(',', $sizes_raw)));

        $variants = [];
        if (!empty($colors_arr)) {
            $variants['colors'] = array_map(function($c) use ($img) {
                return ['name' => $c, 'image' => $img];
            }, $colors_arr);
        }
        if (!empty($sizes_arr)) {
            $variants['sizes'] = array_map(function($s) {
                return ['name' => $s, 'price_offset' => 0];
            }, $sizes_arr);
        }

        $variants_json = json_encode($variants);

        $stmt = $pdo->prepare("INSERT INTO products (store_id, category_id, title, description, price, original_price, stock, sku, trust_score, image_url, variants, ai_summary) VALUES (1, ?, ?, ?, ?, ?, ?, ?, 95, ?, ?, ?)");
        $ai_summary = json_encode([
            'verdict' => 'Verified high quality seller catalog addition.',
            'pros' => ['High quality material', '1 year official warranty'],
            'cons' => [],
            'best_for' => 'Daily Use & Smart Living'
        ]);
        $stmt->execute([$category_id, $title, $description, $price, $price * 1.25, $stock, $sku, $img, $variants_json, $ai_summary]);

        echo json_encode(['status' => 'success', 'message' => 'Product created successfully!', 'id' => $pdo->lastInsertId()]);
        exit;
    }

    if ($action === 'update_stock') {
        $id = intval($_POST['id'] ?? 0);
        $stock = intval($_POST['stock'] ?? 0);
        if ($id) {
            $stmt = $pdo->prepare("UPDATE products SET stock = ? WHERE id = ?");
            $stmt->execute([$stock, $id]);
            echo json_encode(['status' => 'success', 'message' => 'Stock updated successfully.']);
        }
        exit;
    }

    if ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        if ($id) {
            $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(['status' => 'success', 'message' => 'Product removed.']);
        }
        exit;
    }

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
