<?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);

// Sanitize input
$id = intval($_GET['id'] ?? 0);
$amount = floatval($_POST['amount'] ?? 0);
$action = $_POST['action'] ?? '';
$affiliate_pay_amount = 0;

// Get affiliate current balance
$stmt = $mysqli->prepare("SELECT pay_amount FROM affiliate_pay WHERE pay_affiliateid = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($affiliate_pay_amount);
$stmt->fetch();
$stmt->close();

// Validate action
if (($action === "add") || ($action === "deduct" && ($affiliate_pay_amount - $amount) > 0)) {
    switch ($action) {
        case 'add':
            $affiliate_pay_amount += $amount;

            if ($affiliate_pay_amount > $affiliate_maximum_amount) {
                $msg = urlencode("Amount cannot be added since it exceeds the maximum balance amount limit.");
                header("Location: index.php?Act=adjust_affiliate&affid=$id&msg=$msg");
                exit;
            }
            break;

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

    // 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 (?, ?, 'a', ?, ?)");
    $stmt->bind_param("isd", $id, $action, $amount, $today);
    $stmt->execute();
    $stmt->close();

    // Update affiliate balance
    $stmt = $mysqli->prepare("UPDATE affiliate_pay SET pay_amount = ? WHERE pay_affiliateid = ?");
    $stmt->bind_param("di", $affiliate_pay_amount, $id);
    $stmt->execute();
    $stmt->close();

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

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