<?php
// ============================================================
//  MediCore — Investments API
//  File: api/investments.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),
        'add'    => api_add($body),
        'delete' => api_delete($body),
        default  => fail('Unknown action')
    };
} catch (Throwable $e) {
    fail($e->getMessage());
}

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

    $partner = trim($b['partner'] ?? '');
    $type    = trim($b['type']    ?? '');
    $from    = trim($b['from']    ?? '');
    $to      = trim($b['to']      ?? '');

    if ($partner) { $where[] = "partner = ?";  $params[] = $partner; }
    if ($type)    { $where[] = "type = ?";      $params[] = $type;    }
    if ($from)    { $where[] = "date >= ?";     $params[] = $from;    }
    if ($to)      { $where[] = "date <= ?";     $params[] = $to;      }

    $wSql = implode(' AND ', $where);
    $rows = db_rows(
        "SELECT * FROM investments WHERE $wSql ORDER BY date DESC, id DESC",
        $params
    );
    ok(['data' => $rows]);
}

// ── Add ───────────────────────────────────────────────────────
function api_add(array $b): void {
    $partner = trim($b['partner'] ?? '');
    $type    = trim($b['type']    ?? '');
    $amount  = (float)($b['amount'] ?? 0);
    $date    = trim($b['date']    ?? date('Y-m-d'));
    $note    = trim($b['note']    ?? '');

    if (!$partner)    fail('Partner name is required');
    if (!$type)       fail('Transaction type is required');
    if ($amount <= 0) fail('Amount must be greater than zero');

    if (!in_array($type, ['deposit', 'withdraw']))
        fail('Invalid transaction type');

    $id = db_insert(
        "INSERT INTO investments (partner, type, amount, date, note)
         VALUES (?, ?, ?, ?, ?)",
        [$partner, $type, $amount, $date, $note]
    );
    ok(['id' => $id, 'msg' => 'Transaction saved']);
}

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

    $row = db_row("SELECT id FROM investments WHERE id = ?", [$id]);
    if (!$row) fail('Transaction not found');

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