<?php
ob_start();

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

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

// Input sanitization
$id     = intval($_GET['id'] ?? 0);
$amount = floatval($_POST['amount'] ?? 0);
$action = $_POST['action'] ?? '';
$merchant_pay_amount = 0;

// Fetch current merchant balance
$stmt = $mysqli->prepare("SELECT pay_amount FROM merchant_pay WHERE pay_merchantid = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($merchant_pay_amount);
$stmt->fetch();
$stmt->close();

if (($action === "add") || ($action === "deduct" && ($merchant_pay_amount - $amount) > $minimum_amount)) {
    switch ($action) {
        case 'add':
            $merchant_pay_amount += $amount;

            if (!empty($merchant_maximum_amount) && $merchant_pay_amount > $merchant_maximum_amount) {
                $msg = urlencode("Amount cannot be added since it exceeds the maximum balance amount limit.");
                header("Location: index.php?Act=adjust_merchant&merid=$id&msg=$msg");
                exit;
            }
            break;

        case 'deduct':
            $merchant_pay_amount -= $amount;
            break;
    }

    // Update merchant balance
    $stmt = $mysqli->prepare("UPDATE merchant_pay SET pay_amount = ? WHERE pay_merchantid = ?");
    $stmt->bind_param("di", $merchant_pay_amount, $id);
    $stmt->execute();
    $stmt->close();

    // Update merchant status
    if ($merchant_pay_amount > $minimum_amount) {
        $status = 'approved';
    } else {
        $status = 'empty';
    }

    $stmt = $mysqli->prepare("UPDATE partners_merchant SET merchant_status = ? WHERE merchant_id = ?");
    $stmt->bind_param("si", $status, $id);
    $stmt->execute();
    $stmt->close();

    // Log the adjustment
    $today = date("Y-m-d");
    $stmt = $mysqli->prepare("INSERT INTO partners_adjustment (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date) VALUES (?, ?, 'm', ?, ?)");
    $stmt->bind_param("isd", $id, $action, $amount, $today);
    $stmt->execute();
    $stmt->close();

    $msg = urlencode("Amount " . $action . "ed successfully");
} else {
    $msg = urlencode("Sorry Merchant Account doesn't have sufficient amount to do this transaction");
}

// Redirect with message
header("Location: index.php?Act=adjust_merchant&merid=$id&msg=$msg");
exit;
?>
