<?php
// /api/seller/products.php — GET list | POST create | PUT update | DELETE remove
require_once __DIR__ . '/../init.php';

$user = AuthMiddleware::verifyToken();
AuthMiddleware::requireRole(['seller', 'admin']);

$sellerId = (int)$user['id'];
$db       = DB::conn();
$method   = $_SERVER['REQUEST_METHOD'];

// ─── GET — list products ──────────────────────────────────────
if ($method === 'GET') {
    $stmt = $db->prepare(
        'SELECT id, name, description, price, stock, category, image_url, is_active, sold_count, created_at
         FROM products WHERE seller_id = ? ORDER BY created_at DESC'
    );
    $stmt->execute([$sellerId]);
    $products = $stmt->fetchAll();

    foreach ($products as &$p) {
        $p['id']        = (int)$p['id'];
        $p['price']     = (float)$p['price'];
        $p['stock']     = (int)$p['stock'];
        $p['sold_count']= (int)$p['sold_count'];
        $p['is_active'] = (bool)$p['is_active'];
    }
    Response::success('Products fetched.', ['products' => $products]);
}

// ─── POST — create product ────────────────────────────────────
if ($method === 'POST') {
    $body = getBody();
    $name  = trim($body['name']  ?? '');
    $price = (float)($body['price'] ?? 0);
    $stock = (int)($body['stock'] ?? 0);

    if (!$name || $price < 0) Response::error('ชื่อสินค้าและราคาจำเป็น');

    $stmt = $db->prepare(
        'INSERT INTO products (seller_id, name, description, price, stock, category, image_url)
         VALUES (?, ?, ?, ?, ?, ?, ?)'
    );
    $stmt->execute([
        $sellerId,
        $name,
        trim($body['description'] ?? ''),
        $price,
        $stock,
        trim($body['category'] ?? ''),
        trim($body['image_url'] ?? ''),
    ]);
    $newId = (int)$db->lastInsertId();
    Response::success('สร้างสินค้าสำเร็จ', ['id' => $newId], 201);
}

// ─── PUT — update product ─────────────────────────────────────
if ($method === 'PUT') {
    $body      = getBody();
    $productId = (int)($body['id'] ?? 0);
    if (!$productId) Response::error('Product ID required.');

    // Verify ownership
    $stmt = $db->prepare('SELECT id FROM products WHERE id = ? AND seller_id = ?');
    $stmt->execute([$productId, $sellerId]);
    if (!$stmt->fetch()) Response::error('ไม่พบสินค้าหรือคุณไม่มีสิทธิ์', 403);

    $fields = [];
    $params = [];
    foreach (['name','description','price','stock','category','image_url','is_active'] as $f) {
        if (isset($body[$f])) { $fields[] = "`$f` = ?"; $params[] = $body[$f]; }
    }
    if (!$fields) Response::error('No fields to update.');

    $params[] = $productId;
    $db->prepare('UPDATE products SET ' . implode(', ', $fields) . ' WHERE id = ?')->execute($params);
    Response::success('อัปเดตสินค้าสำเร็จ');
}

// ─── DELETE — remove product ──────────────────────────────────
if ($method === 'DELETE') {
    $body      = getBody();
    $productId = (int)($body['id'] ?? 0);
    if (!$productId) Response::error('Product ID required.');

    $stmt = $db->prepare('SELECT id FROM products WHERE id = ? AND seller_id = ?');
    $stmt->execute([$productId, $sellerId]);
    if (!$stmt->fetch()) Response::error('ไม่พบสินค้าหรือคุณไม่มีสิทธิ์', 403);

    $db->prepare('DELETE FROM products WHERE id = ?')->execute([$productId]);
    Response::success('ลบสินค้าสำเร็จ');
}

Response::error('Method not allowed.', 405);
