<?php
ob_start();

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

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

$today = date("Y-m-d");

// Sanitize inputs
$affiliate_id = intval($_GET['affiliate_id'] ?? 0);
$amount = floatval($_GET['amount'] ?? 0);
$request_id = intval($_GET['request_id'] ?? 0);

if ($affiliate_id <= 0 || $amount <= 0 || $request_id <= 0) {
    header("Location: index.php?Act=request&msg=Invalid request parameters");
    exit;
}

$conn = $partners->getConnection(); // assuming your `partners` class has a getConnection() that returns the `mysqli` object

// Delete from partners_request
$stmt = $conn->prepare("DELETE FROM partners_request WHERE request_id = ?");
$stmt->bind_param("i", $request_id);
$stmt->execute();
if ($stmt->error) {
    die("Error deleting request: " . $stmt->error);
}
$stmt->close();

// Insert into partners_adjustment
$stmt = $conn->prepare("INSERT INTO partners_adjustment (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date, adjust_no) VALUES (?, 'withdraw', 'a', ?, ?, 0)");
$stmt->bind_param("ids", $affiliate_id, $amount, $today);
$stmt->execute();
if ($stmt->error) {
    die("Error inserting adjustment: " . $stmt->error);
}
$stmt->close();

// Retrieve current balance
$current_balance = 0;
$stmt = $conn->prepare("SELECT pay_amount FROM affiliate_pay WHERE pay_affiliateid = ?");
$stmt->bind_param("i", $affiliate_id);
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
    $current_balance = floatval($row['pay_amount']);
}
$stmt->close();

// Update new balance
$new_balance = $current_balance - $amount;
if ($new_balance < 0) $new_balance = 0;

$stmt = $conn->prepare("UPDATE affiliate_pay SET pay_amount = ? WHERE pay_affiliateid = ?");
$stmt->bind_param("di", $new_balance, $affiliate_id);
$stmt->execute();
if ($stmt->error) {
    die("Error updating balance: " . $stmt->error);
}
$stmt->close();

// Redirect with success
header("Location: index.php?Act=request&msg=Amount Transferred Successfully");
exit;
