<?php
require_once __DIR__ . '/../../cors.php'; // Enable CORS for React Native
// GET    /api/admin/products — list all products
// POST   /api/admin/products — create product
// PATCH  /api/admin/products — update product
// DELETE /api/admin/products — delete product
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../middleware/auth.php';

requireAdmin();
$db = getDB();

// ---- GET ----
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $products = $db->query('SELECT * FROM products ORDER BY created_at DESC')->fetchAll();
    jsonResponse($products);
}

// ---- POST ----
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $body        = getBody();
    $name        = trim($body['name']        ?? '');
    $description = trim($body['description'] ?? '');
    $price       = (float)($body['price']    ?? 0);
    $category    = trim($body['category']    ?? '');
    $image       = trim($body['image']       ?? '');
    $stock       = (int)($body['stock']      ?? 0);
    $isActive    = isset($body['isActive']) ? (int)(bool)$body['isActive'] : 1;

    if (!$name || !$category || $price <= 0) jsonError('name, category and price are required');

    $id = generateId();
    $db->prepare(
        'INSERT INTO products (id, name, description, price, category, image, stock, is_active)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
    )->execute([$id, $name, $description ?: null, $price, $category, $image ?: null, $stock, $isActive]);

    $stmt = $db->prepare('SELECT * FROM products WHERE id = ?');
    $stmt->execute([$id]);
    jsonResponse($stmt->fetch(), 201);
}

// ---- PATCH ----
if ($_SERVER['REQUEST_METHOD'] === 'PATCH') {
    $body = getBody();
    $id   = $body['id'] ?? '';
    if (!$id) jsonError('Product id is required');

    $fields = [];
    $params = [];

    if (isset($body['name']))        { $fields[] = 'name = ?';        $params[] = trim($body['name']); }
    if (isset($body['description'])) { $fields[] = 'description = ?'; $params[] = trim($body['description']); }
    if (isset($body['price']))       { $fields[] = 'price = ?';       $params[] = (float)$body['price']; }
    if (isset($body['category']))    { $fields[] = 'category = ?';    $params[] = trim($body['category']); }
    if (isset($body['image']))       { $fields[] = 'image = ?';       $params[] = trim($body['image']); }
    if (isset($body['stock']))       { $fields[] = 'stock = ?';       $params[] = (int)$body['stock']; }
    if (isset($body['isActive']))    { $fields[] = 'is_active = ?';   $params[] = (int)(bool)$body['isActive']; }

    if (empty($fields)) jsonError('Nothing to update');

    $fields[]  = 'updated_at = NOW()';
    $params[]  = $id;
    $db->prepare('UPDATE products SET ' . implode(', ', $fields) . ' WHERE id = ?')->execute($params);

    $stmt = $db->prepare('SELECT * FROM products WHERE id = ?');
    $stmt->execute([$id]);
    jsonResponse($stmt->fetch());
}

// ---- DELETE ----
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $body = getBody();
    $id   = $body['id'] ?? '';
    if (!$id) jsonError('Product id is required');
    $db->prepare('DELETE FROM products WHERE id = ?')->execute([$id]);
    jsonResponse(['success' => true]);
}

jsonError('Method not allowed', 405);
