<?php
session_start();
if ($_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}
include '../config/db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $amount = floatval($_POST['amount']);
    $reason = trim($_POST['reason']);
    $deduction_type = $_POST['deduction_type'] ?? 'expense';
    
    // Get current totals
    $total_fund = $conn->query("SELECT COALESCE(SUM(amount),0) FROM donations WHERE status='verified'")->fetch_row()[0] ?? 0;
    $total_additions = $conn->query("SELECT COALESCE(SUM(amount),0) FROM balance_additions")->fetch_row()[0] ?? 0;
    $total_distributed = $conn->query("SELECT COALESCE(SUM(amount),0) FROM fund_distributions")->fetch_row()[0] ?? 0;
    $available_balance = ($total_fund + $total_additions) - $total_distributed;
    
    if ($amount > 0 && $amount <= $available_balance && !empty($reason)) {
        $description = "[DEDUCTION] " . $reason;
        $distributed_to = ucfirst(str_replace('_', ' ', $deduction_type));
        
        $stmt = $conn->prepare("INSERT INTO fund_distributions (description, amount, distributed_to, date) VALUES (?, ?, ?, CURDATE())");
        $stmt->bind_param("sds", $description, $amount, $distributed_to);
        
        if ($stmt->execute()) {
            $admin_id = $_SESSION['user_id'];
            $stmt2 = $conn->prepare("INSERT INTO withdrawal_requests (requested_by, amount, reason, status, requested_at) VALUES (?, ?, ?, 'approved', NOW())");
            $stmt2->bind_param("ids", $admin_id, $amount, $reason);
            $stmt2->execute();
            $stmt2->close();
            
            $_SESSION['success_msg'] = "Successfully deducted ₹" . number_format($amount, 2) . " from the available balance.";
        } else {
            $_SESSION['error_msg'] = "Database error: " . $conn->error;
        }
        $stmt->close();
    } else {
        $_SESSION['error_msg'] = "Invalid amount or insufficient balance.";
    }
    
    header("Location: dashboard.php");
    exit();
}
?>