<?php
session_start();
require_once '../../includes/db.php';

// Security check
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: ../login.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and validate inputs
    $partner_id = filter_input(INPUT_POST, 'partner_id', FILTER_VALIDATE_INT);
    $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
    $payment_method = trim($_POST['payment_method']);
    $notes = trim($_POST['notes']);

    if (!$partner_id || !$amount || $amount <= 0 || empty($payment_method)) {
        $_SESSION['error_message'] = "Invalid payout data provided.";
        header("Location: ../manage-affiliates.php");
        exit();
    }
    
    // You might want to add a server-side check here to ensure the payout amount
    // does not exceed the actual commission due.

    // Prepare and execute the insert into withdrawals table
    $status = 'Completed'; // Admin payouts are instantly completed
    $stmt = $conn->prepare("INSERT INTO withdrawals (partner_id, amount, status, payment_details, admin_notes) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("idsss", $partner_id, $amount, $status, $payment_method, $notes);

    if ($stmt->execute()) {
        $_SESSION['success_message'] = "Payout of ₱" . number_format($amount, 2) . " processed successfully.";
    } else {
        $_SESSION['error_message'] = "Database error: Could not record the payout.";
    }
    $stmt->close();
} else {
    $_SESSION['error_message'] = "Invalid request method.";
}

header("Location: ../manage-affiliates.php");
exit();
?>
