<?php
include('includes/dbconn.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate inputs
    $client_id = $_POST["client_id"] ?? null;
    $invoice_number = $_POST["invoice_number"] ?? '';
    $due_date = $_POST["due_date"] ?? '';
    $fixed_discount = isset($_POST["discount"]) ? (float)$_POST["discount"] : 0.0;
    $tax_percentage = isset($_POST["tax"]) ? (float)$_POST["tax"] : 0.0;
    $quantity = isset($_POST["quantity"]) ? (float)$_POST["quantity"] : 0;
    $unit_price = isset($_POST["unit_price"]) ? (float)$_POST["unit_price"] : 0;
    $description = $_POST["description"][0] ?? ''; // Assuming there's only one description

    // Insert into invoices table with a placeholder total amount
    $insertInvoiceQuery = "INSERT INTO invoices (client_id, invoice_number, total_amount, due_date, discount, tax) VALUES (?, ?, 0, ?, ?, ?)";
    $insertStmt = $conn->prepare($insertInvoiceQuery);
    $insertStmt->bind_param("issdd", $client_id, $invoice_number, $due_date, $fixed_discount, $tax_percentage);
    $insertStmt->execute();
    $invoice_id = $conn->insert_id;

    // Calculate line item total before tax
    $total_before_tax = ($quantity * $unit_price) - $fixed_discount;

    // Calculate tax amount
    $tax_amount = ($tax_percentage / 100) * $total_before_tax;

    // Calculate the final total amount for the line item
    $total_amount_line_item = $total_before_tax + $tax_amount;

    // Insert line item
    $insertLineItemQuery = "INSERT INTO invoice_line_items (invoice_id, description, quantity, unit_price, discount, tax, total_amount) VALUES (?, ?, ?, ?, ?, ?, ?)";
    $insertLineItemStmt = $conn->prepare($insertLineItemQuery);
    $insertLineItemStmt->bind_param("isiddid", $invoice_id, $description, $quantity, $unit_price, $fixed_discount, $tax_amount, $total_amount_line_item);
    $insertLineItemStmt->execute();

    // Update the total_amount in the invoices table
    $updateInvoiceQuery = "UPDATE invoices SET total_amount = ? WHERE invoice_id = ?";
    $updateStmt = $conn->prepare($updateInvoiceQuery);
    $updateStmt->bind_param('di', $total_amount_line_item, $invoice_id);
    $updateStmt->execute();

    // Redirect to invoice details page
    header("Location: invoice_details.php?invoice_id=$invoice_id");
    exit();
} else {
    echo "Error: Invalid request method";
}

$conn->close();
?>
