<?php
ob_start();

include '../includes/session.php';
include '../includes/constants.php';
include '../includes/functions.php';
include '../includes/allstripslashes.php';

$partners = new partners;
$partners->connection($host, $user, $pass, $db);

$conn = $partners->conn;

$affiliate_id = isset($_GET['affiliateid']) ? intval($_GET['affiliateid']) : 0;
$merchant_id  = isset($_GET['merchantid']) ? intval($_GET['merchantid']) : 0;
$amount       = isset($_GET['amount']) ? floatval($_GET['amount']) : 0;
$transid      = isset($_GET['transid']) ? intval($_GET['transid']) : 0;
$today        = date("Y-m-d");

$merchant_pay_amount = 0;

// Get merchant pay record
$stmt = $conn->prepare("SELECT pay_amount FROM merchant_pay WHERE pay_merchantid = ?");
$stmt->bind_param("i", $merchant_id);
$stmt->execute();
$stmt->bind_result($merchant_pay_amount);
$stmt->fetch();
$stmt->close();

if (($merchant_pay_amount - $amount) >= 0) {
    // Update partners_transaction with payment info
    $stmt = $conn->prepare("UPDATE partners_transaction SET transaction_adminpaydate = ?, transaction_adminpaid = ? WHERE transaction_id = ?");
    $stmt->bind_param("sdi", $today, $amount, $transid);
    $stmt->execute();
    $stmt->close();

    // Get admin pay amount
    $admin_pay_amount = 0;
    $admin_query = $conn->query("SELECT pay_amount FROM admin_pay");
    if ($admin_query && $admin_query->num_rows > 0) {
        $admin_row = $admin_query->fetch_assoc();
        $admin_pay_amount = $admin_row['pay_amount'];
    }

    // Update merchant and admin balances
    $new_merchant_amount = $merchant_pay_amount - $amount;
    $new_admin_amount = $admin_pay_amount + $amount;

    $stmt = $conn->prepare("UPDATE merchant_pay SET pay_amount = ? WHERE pay_merchantid = ?");
    $stmt->bind_param("di", $new_merchant_amount, $merchant_id);
    $stmt->execute();
    $stmt->close();

    $stmt = $conn->prepare("UPDATE admin_pay SET pay_amount = ?");
    $stmt->bind_param("d", $new_admin_amount);
    $stmt->execute();
    $stmt->close();

    $msg = "Payment Successfull!!!";
} else {
    $msg = "Payment Failed. No Money in merchant account!!!";
}

$msg = urlencode($msg);
header("Location: index.php?Act=admin_payments&msg=$msg");
exit;
?>
