<?php

require_once 'includes/dbconn.php';
require_once 'includes/functions.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $client_id = $_POST['client_id'];
    $due_date = $_POST['due_date'];

    // Assuming you have a way to collect line items in your form
    $line_items = $_POST['line_items'];

    // Calculate total amount based on line items
    $total_amount = 0;
    foreach ($line_items as $item) {
        $total_amount += $item['quantity'] * $item['unit_price'];
    }

    $invoice_number = generateInvoiceNumber($conn);

    $stmt = $conn->prepare("INSERT INTO invoices (client_id, invoice_number, total_amount, due_date) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("issd", $client_id, $invoice_number, $total_amount, $due_date);

    if ($stmt->execute()) {
        // Retrieve the auto-generated invoice ID
        $invoice_id = $stmt->insert_id;

        // Insert line items into invoice_line_items table
        foreach ($line_items as $item) {
            $description = $item['description'];
            $quantity = $item['quantity'];
            $unit_price = $item['unit_price'];
            $line_total = $quantity * $unit_price;

            $stmt = $conn->prepare("INSERT INTO invoice_line_items (invoice_id, description, quantity, unit_price, total_amount) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("isddd", $invoice_id, $description, $quantity, $unit_price, $line_total);
            $stmt->execute();
        }

        header("Location: invoices.php");
        exit();
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
    $conn->close();
}

?>
