<?php
// ============================================================
//  MediCore — Companies API
//  File: api/companies.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());
}

// ── List / Search ─────────────────────────────────────────────
function api_list(array $b): void {
    $q = trim($b['q'] ?? '');
    $params = [];
    $where  = '';

    if ($q) {
        $where    = "WHERE c.name LIKE ?";
        $params[] = "%$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 companies c $where", $params);

    $rows = db_rows(
        "SELECT c.*,
                COUNT(p.id) AS product_count
           FROM companies c
      LEFT JOIN products p ON p.company_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)),
    ]);
}

// ── Detail ────────────────────────────────────────────────────
function api_detail(array $b): void {
    $id = (int)($b['id'] ?? 0);
    if (!$id) fail('Missing id');

    $row = db_row("SELECT * FROM companies WHERE id = ?", [$id]);
    if (!$row) fail('Company not found');
    ok(['data' => $row]);
}

// ── Add ───────────────────────────────────────────────────────
function api_add(array $b): void {
    $name    = trim($b['name']    ?? '');
    $country = trim($b['country'] ?? 'Bangladesh');
    if (!$name) fail('Company name is required');

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

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

// ── Edit ──────────────────────────────────────────────────────
function api_edit(array $b): void {
    $id      = (int)($b['id']      ?? 0);
    $name    = trim($b['name']     ?? '');
    $country = trim($b['country']  ?? 'Bangladesh');
    if (!$id)   fail('Missing id');
    if (!$name) fail('Company name is required');

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

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

// ── Delete ────────────────────────────────────────────────────
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 company_id = ? AND is_active = 1",
        [$id]
    );
    if ($used) fail("Cannot delete — $used product(s) are assigned to this company");

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