false, 'message' => '', 'invoice_id' => 0 ); // Check if the request is POST if ($_SERVER['REQUEST_METHOD'] === 'POST') { // echo '
';
    // print_r($_POST);
    // die();
    try {
        // Start transaction
        $conn->begin_transaction();

        // Get invoice header data
        $consignorName = $_POST['consignorName'];
        $consignorAddress = $_POST['consignorAddress'];
        $consignorPhone = $_POST['consignorPhone'];
        $consignorPincode = $_POST['consignorPincode'];
        $consigneeName = $_POST['consigneeName'];
        $consigneeAddress = $_POST['consigneeAddress'];
        $buyerName = $_POST['buyerName'];
        $buyerAddress = $_POST['buyerAddress'];
        $invoiceNo = $_POST['invoiceNo'];
        $invoiceDate = $_POST['invoiceDate'];
        $deliveryNote = $_POST['deliveryNote'];
        $paymentTerms = $_POST['paymentTerms'];
        $reference = $_POST['reference'];
        $otherReferences = $_POST['otherReferences'];
        $buyerOrderNo = $_POST['buyerOrderNo'];
        $buyerOrderDate = $_POST['buyerOrderDate'];
        $dispatchDocNo = $_POST['dispatchDocNo'];
        $deliveryNoteDate = $_POST['deliveryNoteDate'];
        $dispatchedThrough = $_POST['dispatchedThrough'];
        $destination = $_POST['destination'];
        $termsOfDelivery = $_POST['termsOfDelivery'];
        $totalAmount = $_POST['totalAmount'];
        $amountInWords = $_POST['amountInWords'];
        $remarks = $_POST['remarks'];
        $declaration = $_POST['declaration'];
        $extraDescription = $_POST['extraDescription'];

        // Insert invoice header
        $sql = "INSERT INTO invoices (
                    consignor_name, consignor_address, consignor_phone, consignor_pincode,
                    consignee_name, consignee_address, buyer_name, buyer_address,
                    invoice_no, invoice_date, delivery_note, payment_terms,
                    reference_no, other_references, buyer_order_no, buyer_order_date,
                    dispatch_doc_no, delivery_note_date, dispatched_through, destination,
                    terms_of_delivery, total_amount, amount_in_words, remarks, declaration, extra_desc,
                    created_at
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW()
                )";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param(
            "ssssssssssssssssssssssssss",
            $consignorName,
            $consignorAddress,
            $consignorPhone,
            $consignorPincode,
            $consigneeName,
            $consigneeAddress,
            $buyerName,
            $buyerAddress,
            $invoiceNo,
            $invoiceDate,
            $deliveryNote,
            $paymentTerms,
            $reference,
            $otherReferences,
            $buyerOrderNo,
            $buyerOrderDate,
            $dispatchDocNo,
            $deliveryNoteDate,
            $dispatchedThrough,
            $destination,
            $termsOfDelivery,
            $totalAmount,
            $amountInWords,
            $remarks,
            $declaration,
            $extraDescription
        );

        $stmt->execute();
        $invoiceId = $conn->insert_id;

        // Get invoice items data
        function implodeIfArray($input)
        {
            return is_array($input) ? implode(',', $input) : $input;
        }

        $descriptions = implodeIfArray($_POST['description'] ?? '');
        $qtyShipped = implodeIfArray($_POST['qtyShipped'] ?? '');
        $qtyBilled = implodeIfArray($_POST['qtyBilled'] ?? '');
        $rates = implodeIfArray($_POST['rate'] ?? '');
        $hsn = implodeIfArray($_POST['hsn'] ?? '');
        $pers = implodeIfArray($_POST['per'] ?? '');
        $amounts = implodeIfArray($_POST['amount'] ?? '');


        // Insert invoice items
        $sql = "INSERT INTO invoice_items (
                    invoice_id, description, hsn, qty_shipped, qty_billed, rate, per, amount
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn->prepare($sql);

        $stmt->bind_param(
            "isiddssd",
            $invoiceId,
            $descriptions,
            $hsn,
            $qtyShipped,
            $qtyBilled,
            $rates,
            $pers,
            $amounts
        );
        $stmt->execute();
        // for ($i = 0; $i < count($descriptions); $i++) {
        //     if (!empty($descriptions[$i])) {
        //     }
        // }

        // Commit transaction
        $conn->commit();

        $response['success'] = true;
        $response['message'] = 'Invoice saved successfully';
        $response['invoice_id'] = $invoiceId;
    } catch (Exception $e) {
        // Rollback transaction if failed
        $conn->rollback();
        $response['message'] = 'Error: ' . $e->getMessage();
    }
}

// Return JSON response
header('Content-Type: application/json');
echo json_encode($response);