<?php
include 'config.php';
if($_SESSION['user_role'] != 'SuperAdmin') exit();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $agency_id = $_POST['agency_id'];
    $desc      = $_POST['description'];
    $amount    = $_POST['amount'];
    $due_date  = $_POST['due_date'];

    $stmt = $conn->prepare("INSERT INTO invoices (agency_id, description, amount, due_date) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("isds", $agency_id, $desc, $amount, $due_date);
    
    if ($stmt->execute()) {
        $last_id = $stmt->insert_id;
        // Increase balance due
        $conn->query("UPDATE agencies SET balance_due = balance_due + $amount WHERE id = $agency_id");
        
        // Redirect to the newly created invoice for downloading
        header("Location: view_invoice.php?id=$last_id");
    } else {
        echo "Error: " . $conn->error;
    }
}
?>