<?php
session_start();
include '../includes/connection.php';

// Redirect to login if user not authenticated
if (!isset($_SESSION['authenticated_user']) || $_SESSION['authenticated_user'] !== true) {
    header("Location: /LoanApprovalPredction/login.php");
    exit;
}

$mid = $_SESSION['Mid'];

// Check DB connection
if ($conn->connect_error) {
    die("Database connection failed: " . $conn->connect_error);
}

// Get all balances for this Mid
$stmt = $conn->prepare("SELECT BalanceID, Amount, TransactionUUID FROM balance WHERE Mid = ?");
if (!$stmt) {
    die("SQL error in prepare(): " . $conn->error);
}
$stmt->bind_param("i", $mid);
$stmt->execute();
$result = $stmt->get_result();
$rows = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

if (count($rows) > 1) {
    $total = 0;
    $keep_id = null;
    $keep_txn = null;

    foreach ($rows as $row) {
        $total += (float)$row['Amount'];

        // Prefer row with a non-empty TransactionUUID
        if ($keep_id === null || (empty($keep_txn) && !empty($row['TransactionUUID']))) {
            $keep_id = $row['BalanceID'];
            $keep_txn = $row['TransactionUUID'];
        }
    }

    // Delete all rows except the one to keep
    $stmt = $conn->prepare("DELETE FROM balance WHERE Mid = ? AND BalanceID != ?");
    if (!$stmt) {
        die("Delete prepare() failed: " . $conn->error);
    }
    $stmt->bind_param("ii", $mid, $keep_id);
    $stmt->execute();
    $stmt->close();

    // Update the kept row with the merged amount
    $stmt = $conn->prepare("UPDATE balance SET Amount = ? WHERE BalanceID = ?");
    if (!$stmt) {
        die("Update prepare() failed: " . $conn->error);
    }
    $stmt->bind_param("di", $total, $keep_id);
    $stmt->execute();
    $stmt->close();
}
?>
