<?php
// ============================================================
//  MediCore — Categories API
//  File: api/categories.php
//  Mirrors api/generics.php exactly — a simple id+name lookup used
//  to group/filter/report on products (in addition to the existing
//  generic_id/company_id/form fields).
// ============================================================
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_login();

ensure_categories_schema();

header('Content-Type: application/json');

$body   = json_decode(file_get_contents('php://input'), true) ?? [];
$action = trim($body['action'] ?? '');

try {
    match($action) {
        'list'   => api_list($body),
        'detail' => api_detail($body),
        'add'    => api_add($body),
        'edit'   => api_edit($body),
        'delete' => api_delete($body),
        default  => fail('Unknown action')
    };
} catch (Throwable $e) {
    fail($e->getMessage());
}

function api_list(array $b): void {
    $q      = trim($b['q'] ?? '');
    $where  = $q ? "WHERE c.name LIKE ?" : '';
    $params = $q ? ["%$q%"] : [];

    // ── Pagination ──────────────────────────────────────────────
    $page     = max(1, (int)($b['page'] ?? 1));
    $pageSize = (int)($b['page_size'] ?? 50);
    $pageSize = max(10, min(200, $pageSize));
    $offset   = ($page - 1) * $pageSize;

    $total = (int) db_val("SELECT COUNT(*) FROM categories c $where", $params);

    $rows = db_rows(
        "SELECT c.*, COUNT(p.id) AS product_count
           FROM categories c
      LEFT JOIN products p ON p.category_id = c.id AND p.is_active = 1
         $where
         GROUP BY c.id
         ORDER BY c.name
         LIMIT $pageSize OFFSET $offset",
        $params
    );

    ok([
        'data'        => $rows,
        'page'        => $page,
        'page_size'   => $pageSize,
        'total'       => $total,
        'total_pages' => (int) max(1, ceil($total / $pageSize)),
    ]);
}

function api_detail(array $b): void {
    $id = (int)($b['id'] ?? 0);
    if (!$id) fail('Missing id');
    $row = db_row("SELECT * FROM categories WHERE id = ?", [$id]);
    if (!$row) fail('Category not found');
    ok(['data' => $row]);
}

function api_add(array $b): void {
    $name = trim($b['name'] ?? '');
    if (!$name) fail('Category name is required');

    if (db_val("SELECT id FROM categories WHERE name = ?", [$name]))
        fail("\"$name\" already exists");

    $id = db_insert("INSERT INTO categories (name) VALUES (?)", [$name]);
    ok(['id' => $id, 'msg' => 'Category added']);
}

function api_edit(array $b): void {
    $id   = (int)($b['id']   ?? 0);
    $name = trim($b['name']  ?? '');
    if (!$id)   fail('Missing id');
    if (!$name) fail('Category name is required');

    if (db_val("SELECT id FROM categories WHERE name = ? AND id != ?", [$name, $id]))
        fail("\"$name\" already exists");

    db_run("UPDATE categories SET name = ? WHERE id = ?", [$name, $id]);
    ok(['msg' => 'Category updated']);
}

function api_delete(array $b): void {
    require_admin();
    $id = (int)($b['id'] ?? 0);
    if (!$id) fail('Missing id');

    $used = db_val(
        "SELECT COUNT(*) FROM products WHERE category_id = ? AND is_active = 1", [$id]
    );
    if ($used) fail("Cannot delete — $used product(s) use this category");

    db_run("DELETE FROM categories WHERE id = ?", [$id]);
    ok(['msg' => 'Category deleted']);
}

function ok(array $extra = []): void {
    echo json_encode(array_merge(['success' => true], $extra));
    exit;
}
function fail(string $msg): never {
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}
