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

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

switch ($method) {
    case 'GET':
        $stmt = $db->query('SELECT * FROM categories ORDER BY name ASC');
        $categories = $stmt->fetchAll();
        jsonResponse(['status' => 'success', 'data' => $categories]);
        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 kategori wajib diisi'], 400);
        }
        $stmt = $db->prepare('INSERT INTO categories (name, description) VALUES (?, ?)');
        $stmt->execute([$name, trim($input['description'] ?? '')]);
        jsonResponse(['status' => 'success', 'id' => $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);
        }
        $name = trim($input['name'] ?? '');
        if (empty($name)) {
            jsonResponse(['status' => 'error', 'message' => 'Nama kategori wajib diisi'], 400);
        }
        $stmt = $db->prepare('UPDATE categories SET name = ?, description = ? WHERE id = ?');
        $stmt->execute([$name, trim($input['description'] ?? ''), $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 categories WHERE id = ? AND NOT EXISTS (SELECT 1 FROM products WHERE category_id = ?)');
        $stmt->execute([$id, $id]);
        if ($stmt->rowCount() === 0) {
            jsonResponse(['status' => 'error', 'message' => 'Gagal hapus. Kategori mungkin masih punya produk.'], 400);
        }
        jsonResponse(['status' => 'success']);
        break;
}
