<?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']);
    $description = trim($_POST['description']);
    $source = trim($_POST['source']);
    $admin_id = $_SESSION['user_id'];
    
    if ($amount <= 0) {
        $_SESSION['error_msg'] = "Please enter a valid amount greater than 0.";
    } elseif (empty($description)) {
        $_SESSION['error_msg'] = "Please provide a description for this addition.";
    } else {
        // Insert into balance_additions table
        $stmt = $conn->prepare("INSERT INTO balance_additions (amount, source, description, added_by, added_at) VALUES (?, ?, ?, ?, NOW())");
        $stmt->bind_param("dssi", $amount, $source, $description, $admin_id);
        
        if ($stmt->execute()) {
            $_SESSION['success_msg'] = "✅ Successfully added ₹" . number_format($amount, 2) . " to the available balance!";
        } else {
            $_SESSION['error_msg'] = "Database error: " . $conn->error;
        }
        $stmt->close();
    }
    
    header("Location: dashboard.php");
    exit();
}
?>