<?php

/**
 * Upserts fee_records (same composite key and behaviour as payschoolfees.php saveFeeRecord).
 *
 * @return bool True on success
 */
function fee_records_upsert(mysqli $con, string $name, string $class, string $stream, string $student_type, string $session, string $term, float $amount): bool
{
    $stmt = $con->prepare("SELECT id FROM fee_records WHERE class = ? AND stream = ? AND student_type = ? AND session = ? AND term = ? AND name = ? LIMIT 1");
    if (!$stmt) {
        return false;
    }
    $stmt->bind_param("ssssss", $class, $stream, $student_type, $session, $term, $name);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows === 0) {
        $stmt->close();
        $ins = $con->prepare("INSERT INTO fee_records (name, class, stream, student_type, session, term, amount) VALUES (?, ?, ?, ?, ?, ?, ?)");
        if (!$ins) {
            return false;
        }
        $ins->bind_param("ssssssd", $name, $class, $stream, $student_type, $session, $term, $amount);
        $ok = $ins->execute();
        $ins->close();
        return $ok;
    }
    $stmt->bind_result($feeRecordId);
    $stmt->fetch();
    $stmt->close();
    $upd = $con->prepare("UPDATE fee_records SET amount = ? WHERE id = ?");
    if (!$upd) {
        return false;
    }
    $upd->bind_param("di", $amount, $feeRecordId);
    $ok = $upd->execute();
    $upd->close();
    return $ok;
}
