<?php
require_once 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
    $action = $_GET['action'] ?? '';

    if ($action === 'add') {
        $id = uniqid('p_');
        $stmt = $pdo->prepare("INSERT INTO products (
            id, name, price, old_price, disc, seed, vendorEmail, category, description, summary, images, colors, sizes, is_flash, is_top
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $id, 
            $data['name'], 
            $data['price'], 
            $data['old'] ?? null, 
            $data['disc'] ?? null, 
            $data['seed'] ?? 'prod',
            $data['vendorEmail'] ?? '',
            $data['category'] ?? '',
            $data['description'] ?? '',
            $data['summary'] ?? '',
            isset($data['images']) ? json_encode($data['images']) : null,
            isset($data['colors']) ? json_encode($data['colors']) : null,
            isset($data['sizes']) ? json_encode($data['sizes']) : null,
            isset($data['is_flash']) ? (int)$data['is_flash'] : 0,
            isset($data['is_top']) ? (int)$data['is_top'] : 0
        ]);
        echo json_encode(['success' => true, 'id' => $id]);
    } else if ($action === 'delete') {
        $id = $data['id'];
        $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
        $stmt->execute([$id]);
        echo json_encode(['success' => true]);
    } else if ($action === 'edit') {
        $id = $data['id'];
        $stmt = $pdo->prepare("UPDATE products SET 
            name = ?, price = ?, old_price = ?, disc = ?, category = ?, 
            description = ?, summary = ?, images = ?, colors = ?, sizes = ?,
            is_flash = ?, is_top = ?
            WHERE id = ?");
        $stmt->execute([
            $data['name'], 
            $data['price'], 
            $data['old'] ?? null, 
            $data['disc'] ?? null, 
            $data['category'] ?? '',
            $data['description'] ?? '',
            $data['summary'] ?? '',
            isset($data['images']) ? json_encode($data['images']) : null,
            isset($data['colors']) ? json_encode($data['colors']) : null,
            isset($data['sizes']) ? json_encode($data['sizes']) : null,
            isset($data['is_flash']) ? (int)$data['is_flash'] : 0,
            isset($data['is_top']) ? (int)$data['is_top'] : 0,
            $id
        ]);
        echo json_encode(['success' => true]);
    }
}
?>
