<?php
// ============================================================
//  MediCore — Cash Ledger API
//  File: api/cash.php
// ============================================================
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_login();
session_write_close(); // release session lock — prevents XAMPP request queuing

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

ensure_sync_tables();

$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 with filters ─────────────────────────────────────────
function api_list(array $b): void {
    $where  = ['1=1'];
    $params = [];

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

    $validAccounts = ['Cash','Card','Bank','MFS'];
    $validTypes    = ['in','out'];

    if ($account && in_array($account, $validAccounts)) {
        $where[] = "account = ?"; $params[] = $account;
    }
    if ($type && in_array($type, $validTypes)) {
        $where[] = "type = ?"; $params[] = $type;
    }
    if ($from) { $where[] = "date >= ?"; $params[] = $from; }
    if ($to)   { $where[] = "date <= ?"; $params[] = $to;   }
    if ($q)    {
        $where[]  = "(description LIKE ? OR ref LIKE ?)";
        $params[] = "%$q%"; $params[] = "%$q%";
    }

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

// ── Add manual entry ──────────────────────────────────────────
function api_add(array $b): void {
    $desc    = trim($b['desc']    ?? '');
    $account = trim($b['account'] ?? 'Cash');
    $type    = trim($b['type']    ?? 'in');
    $amount  = (float)($b['amount'] ?? 0);
    $date    = trim($b['date']    ?? date('Y-m-d'));
    $ref     = trim($b['ref']     ?? '');

    if (!$desc)     fail('Description is required');
    if ($amount <= 0) fail('Amount must be greater than zero');

    $validAccounts = ['Cash','Card','Bank','MFS'];
    $validTypes    = ['in','out'];
    if (!in_array($account, $validAccounts)) fail('Invalid account');
    if (!in_array($type,    $validTypes))    fail('Invalid type');

    // Prefix ref with MAN- so it can be identified and deleted
    $manRef = 'MAN-' . date('YmdHis') . ($ref ? '-' . substr($ref, 0, 20) : '');

    $id = db_insert(
        "INSERT INTO cash_ledger
           (date, description, account, type, amount, ref)
         VALUES (?, ?, ?, ?, ?, ?)",
        [$date, $desc, $account, $type, $amount, $manRef]
    );
    enqueue_sync('cash_ledger', $id, 'INSERT', db_row("SELECT * FROM cash_ledger WHERE id = ?", [$id]));
    ok(['id' => $id, 'msg' => 'Entry added']);
}

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

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

    // Only allow deleting manual entries (ref starts with MAN-)
    if (!str_starts_with($row['ref'] ?? '', 'MAN-'))
        fail('Only manual entries can be deleted. System entries are protected.');

    db_run("DELETE FROM cash_ledger WHERE id = ?", [$id]);
    // A genuine hard delete (cash_ledger has no soft-delete column) — this
    // is the one place in the app where operation_type = 'DELETE' actually
    // means "remove the row", not "flip is_deleted". No payload is needed;
    // the Cloud receiver just needs table_name + record_id to delete its copy.
    enqueue_sync('cash_ledger', $id, 'DELETE');
    ok(['msg' => 'Entry 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;
}
