<?php
// api-products.php
require_once __DIR__ . '/config.php';

$method = $_SERVER['REQUEST_METHOD'];
$db = getDB();

switch ($method) {
    case 'GET':
        $stmt = $db->query('
            SELECT p.*, c.name AS category_name, c.id AS category_id
            FROM products p
            LEFT JOIN categories c ON p.category_id = c.id
            WHERE p.status = 1
            ORDER BY c.name, p.name
        ');
        $products = [];
        while ($row = $stmt->fetch()) {
            $products[] = [
                'id' => (int)$row['id'],
                'category_id' => $row['category_id'] ? (int)$row['category_id'] : null,
                'name' => $row['name'],
                'description' => $row['description'],
                'image' => $row['image'] ?: '',
                'price' => $row['price'],
                'stock' => (int)$row['stock'],
                'status' => (int)$row['status'],
                'is_favorite' => (int)$row['is_favorite'],
                'created_at' => $row['created_at'],
                'updated_at' => $row['updated_at'],
                'category' => $row['category_id'] ? [
                    'id' => (int)$row['category_id'],
                    'name' => $row['category_name'],
                ] : null,
            ];
        }
        jsonResponse(['status' => 'success', 'data' => $products]);
        break;

    case 'POST':
        requireAdmin();
        $input = json_decode(file_get_contents('php://input'), true);
        $name = trim($input['name'] ?? '');
        if (empty($name)) {
            jsonResponse(['status' => 'error', 'message' => 'Nama produk wajib diisi'], 400);
        }
        $categoryId = empty($input['category_id']) ? null : (int)$input['category_id'];
        $price = preg_replace('/[^0-9]/', '', $input['price'] ?? '0');
        $stmt = $db->prepare('INSERT INTO products (category_id, name, description, image, price, stock, status, is_favorite) VALUES (?,?,?,?,?,?,?,?)');
        $stmt->execute([
            $categoryId,
            $name,
            trim($input['description'] ?? ''),
            $input['image'] ?? '',
            $price ?: '0',
            (int)($input['stock'] ?? 0),
            (int)($input['status'] ?? 1),
            (int)($input['is_favorite'] ?? 0),
        ]);
        jsonResponse(['status' => 'success', 'id' => (int)$db->lastInsertId()]);
        break;

    case 'PUT':
        requireAdmin();
        $input = json_decode(file_get_contents('php://input'), true);
        $id = (int)($input['id'] ?? 0);
        if ($id <= 0) {
            jsonResponse(['status' => 'error', 'message' => 'ID tidak valid'], 400);
        }
        $categoryId = empty($input['category_id']) ? null : (int)$input['category_id'];
        $price = preg_replace('/[^0-9]/', '', $input['price'] ?? '0');
        $stmt = $db->prepare('UPDATE products SET category_id=?, name=?, description=?, image=?, price=?, stock=?, status=?, is_favorite=? WHERE id=?');
        $stmt->execute([
            $categoryId,
            trim($input['name'] ?? ''),
            trim($input['description'] ?? ''),
            $input['image'] ?? '',
            $price ?: '0',
            (int)($input['stock'] ?? 0),
            (int)($input['status'] ?? 1),
            (int)($input['is_favorite'] ?? 0),
            $id,
        ]);
        jsonResponse(['status' => 'success']);
        break;

    case 'DELETE':
        requireAdmin();
        $input = json_decode(file_get_contents('php://input'), true);
        $id = (int)($input['id'] ?? 0);
        if ($id <= 0) {
            jsonResponse(['status' => 'error', 'message' => 'ID tidak valid'], 400);
        }
        $stmt = $db->prepare('DELETE FROM products WHERE id = ?');
        $stmt->execute([$id]);
        jsonResponse(['status' => 'success']);
        break;
}
