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'] ?? '';
        $consignorGst = $_POST['consignorGst'] ?? '';
        $consigneeName = $_POST['consigneeName'] ?? '';
        $consigneeAddress = $_POST['consigneeAddress'] ?? '';
        $buyerName = $consigneeName;
        $buyerAddress = $consigneeAddress;
        $destination = $_POST['destination'] ?? '';
        $invoiceNo = $_POST['invoiceNo'] ?? '';
        $invoiceDate = $_POST['invoiceDate'] ?? '';
        $deliveryNote = $_POST['deliveryNote'] ?? 'N/A';
        $paymentTerms = $_POST['paymentTerms'] ?? '';
        $reference = $_POST['reference'] ?? 'N/A';
        $buyerOrderDate = $_POST['buyerOrderDate'] ?? '';
        $d_vehicle_date = $_POST['d_vehicle_date'] ?? '';
        $otherReferences = $_POST['otherReferences'] ?? 'N/A';
        $buyerOrderNo = $_POST['buyerOrderNo'] ?? 'N/A';
        $dispatchDocNo = $_POST['dispatchDocNo'] ?? 'N/A';
        $deliveryNoteDate = $_POST['deliveryNoteDate'] ?? 'N/A';
        $dispatchedThrough = $_POST['dispatchedThrough'] ?? 'N/A';
        $termsOfDelivery = $_POST['termsOfDelivery'] ?? '';
        $remarks = $_POST['remarks'] ?? 'N/A';
        $declaration = $_POST['declaration'] ?? '';
        $total_qty = $_POST['total-qty'];
        $total_rate = $_POST['total-rate'];
        $total_amount = $_POST['total-amount'];
        // $vehicleNo = $_POST['vehicleNo'];

        $vehicleNo = isset($_POST['vehicleNo']) ? array_map('trim', $_POST['vehicleNo']) : [];
        $challanNos = isset($_POST['challanNos']) ? array_map('trim', $_POST['challanNos']) : [];
        $dates = isset($_POST['dates']) ? array_map('trim', $_POST['dates']) : [];
        $weights = isset($_POST['weight']) ? array_map('trim', $_POST['weight']) : [];

        $w_o_no = isset($_POST['w_o_no']) ? array_map('trim', $_POST['w_o_no']) : [];
        $rate = isset($_POST['rate']) ? array_map('trim', $_POST['rate']) : [];
        $sub_total = isset($_POST['sub_total']) ? array_map('trim', $_POST['sub_total']) : [];

        // Convert arrays to comma-separated strings
        $challanNosStr = implode(',', $challanNos);
        $vehicleNos = implode(',', $vehicleNo);
        $datesStr = implode(',', $dates);
        $weightsStr = implode(',', $weights);
        $w_o_noStr = implode(',', $w_o_no);
        $rateStr = implode(',', $rate);
        $sub_totalStr = implode(',', $sub_total);


        // Insert invoice header
        $sql = "INSERT INTO challan_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, remarks, declaration, total_qty, total_rate, total_amount, d_vehicle_date,
                    created_at
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW()
                )";

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

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

        // Insert invoice items
        $sql = "INSERT INTO challan_invoice_items (
                    invoice_id, challanNos, weight, dates, w_o_no, rate, sub_total, vehicleNos
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

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

        $stmt->bind_param(
            "isssssss",
            $invoiceId,
            $challanNosStr,
            $weightsStr,
            $datesStr,
            $w_o_noStr,
            $rateStr,
            $sub_totalStr,
            $vehicleNos
        );
        $stmt->execute();
        // for ($i = 0; $i < count($descriptions); $i++) {
        //     if (!empty($descriptions[$i])) {
        //     }
        // }

        // Update challan records to link them with the invoice
        $updateStmt = $conn->prepare("UPDATE `road_challans` SET `chalan_inv` = ? WHERE `challan_no` = ?");
        foreach ($challanNos as $challanNo) {
            $updateStmt->bind_param('ss', $invoiceNo, $challanNo);
            $updateStmt->execute();
        }

        // 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);