<?php
if (isset($_POST['submit_invoice'])) {
    // Validate total_num
    if (!isset($_POST["total_num"]) || empty($_POST["total_num"])) {
        $_SESSION['msg'] = "Error: total_num is missing or empty.";
        $_SESSION['type'] = "danger";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }

    $student_name = inject_checker($connection, $_POST['student_name']);
    $admission_number = inject_checker($connection, $_POST['admission_number']);
    $student_class = inject_checker($connection, $_POST['student_class']);
    $grand_total = inject_checker($connection, $_POST['grand_total']);
    $date = date('Y-m-d');

    // Insert into invoices
    $invoice_stmt = $connection->prepare("INSERT INTO invoices (student_name, admission_number, class, total_amount, date_of_upload) VALUES (?, ?, ?, ?, ?)");
    $invoice_stmt->bind_param("sssds", $student_name, $admission_number, $student_class, $grand_total, $date);

    if ($invoice_stmt->execute()) {
        $invoice_id = $invoice_stmt->insert_id;
        $invoice_stmt->close();

        // Prepare to insert invoice items
        $item_stmt = $connection->prepare("INSERT INTO invoice_items (invoice_id, item_name, unit_price, quantity, total_cost) VALUES (?, ?, ?, ?, ?)");
        $item_stmt->bind_param("isidd", $invoice_id, $item_name, $unit_price, $quantity, $total_cost);

        $total_num = (int)$_POST["total_num"];
        $inserted = 0;

        for ($j = 0; $j < $total_num; $j++) {
            $item_name = inject_checker($connection, $_POST['item_name'][$j]);
            $unit_price = floatval($_POST['unit_price'][$j]);
            $quantity = intval($_POST['quantity'][$j]);

            if (empty($item_name) || $unit_price <= 0 || $quantity <= 0) continue;

            $total_cost = $unit_price * $quantity;
            $item_stmt->execute();
            $inserted++;
        }

        $item_stmt->close();

        if ($inserted > 0) {
            $_SESSION['msg'] = "Invoice submitted successfully with $inserted item(s).";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "Invoice created but no valid items were submitted.";
            $_SESSION['type'] = "warning";
        }
    } else {
        $_SESSION['msg'] = "Failed to insert invoice: " . $invoice_stmt->error;
        $_SESSION['type'] = "danger";
    }

    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}
?>

