<?php
// ============================================================
//  MediCore — Generics API
//  File: api/generics.php
// ============================================================
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_login();

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 g.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 generics g $where", $params);

    $rows = db_rows(
        "SELECT g.*, COUNT(p.id) AS product_count
           FROM generics g
      LEFT JOIN products p ON p.generic_id = g.id AND p.is_active = 1
         $where
         GROUP BY g.id
         ORDER BY g.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 generics WHERE id = ?", [$id]);
    if (!$row) fail('Generic not found');
    ok(['data' => $row]);
}

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

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

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

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

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

    db_run("UPDATE generics SET name = ? WHERE id = ?", [$name, $id]);
    ok(['msg' => 'Generic 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 generic_id = ? AND is_active = 1", [$id]
    );
    if ($used) fail("Cannot delete — $used product(s) use this generic");

    db_run("DELETE FROM generics WHERE id = ?", [$id]);
    ok(['msg' => 'Generic 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;
}
