<?php
$host = 'localhost';
$db   = 'kufgkmxh_loan';
$user = 'kufgkmxh_ussd';
$pass = 'B80P4bGqN7NUyk';

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die("DB connection failed: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $paybill  = $_POST['paybill'] ?? '';
    $account  = $_POST['account_ref'] ?? '';

    if (!empty($paybill) && !empty($account)) {
        // Update the record with ussd = '702-52'
        $stmt = $conn->prepare("
            UPDATE ussd_mpesa_credentials
            SET account = ?, party_b = ?
            WHERE ussd = '90'
        ");
        $stmt->bind_param("ss", $account, $paybill);

        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                $success = "Record updated successfully.";
            } else {
                $error = "No matching record found to update.";
            }
        } else {
            $error = "Database update failed: " . $stmt->error;
        }

        $stmt->close();
    } else {
        $error = "Both Paybill and Account Reference are required.";
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
  <title>Submission Result</title>
</head>
<body style="text-align: center; font-family: sans-serif; padding-top: 50px;">
  <?php if (!empty($success)): ?>
    <h2 style="color: green;">🎉 <?php echo $success; ?></h2>
  <?php else: ?>
    <h2 style="color: red;">⚠️ Error: <?php echo $error ?? 'Unknown error'; ?></h2>
  <?php endif; ?>
  <a href="index.php" style="text-decoration: none; font-size: 18px;">⬅️ Back</a>
</body>
</html>
