<?php
require_once __DIR__ . '/../../core/db_connect.php';

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

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

$tenant_id = (int)($data['tenant_id'] ?? 0);
$fee_type  = trim((string)($data['fee_type'] ?? ''));
$active    = (int)($data['active'] ?? 0);
$amount    = (float)($data['amount'] ?? 0);

if ($tenant_id < 1 || $fee_type === '') {
    echo json_encode(['status' => 'err', 'msg' => 'Invalid data']);
    exit;
}

// Resolve landlord for this tenant to satisfy NOT NULL FK on extra_fees.landlord_id
$st = $conn_rbe->prepare('SELECT landlord_id FROM tenant_landlord_map WHERE tenant_id = ? LIMIT 1');
$st->execute([$tenant_id]);
$landlord_id = (int)$st->fetchColumn();
if ($landlord_id < 1) {
    echo json_encode(['status' => 'err', 'msg' => 'No landlord mapping for tenant']);
    exit;
}

// insert or update
$stmt = $conn_rbe->prepare("
    INSERT INTO extra_fees (tenant_id, landlord_id, fee_type, amount, active)
    VALUES (?, ?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE amount = VALUES(amount), active = VALUES(active)
");
$stmt->execute([$tenant_id, $landlord_id, $fee_type, $amount, $active]);

echo json_encode(['status' => 'ok']);
